df <- expand.grid(x=letters[1:4],
y=1:2)Week4: column and row operations in dataframe
R-basic
Welcome to the fourth course! You will learn dataframe wrangling:
Learning goals
- data frame wrangling with
dplyrandtidyr
1 more mutate examples
Create a dataframe
1.1 combine columns
paste, interaction , unite Compare the results
df%>% mutate(paste(x,y))
df%>% mutate(z=paste(x,y))
df%>% mutate(z=paste(x,y,sep = "-"))
df %>% tidyr::unite(data = .,col = "z",c(x,y))
df <- df %>% mutate(z=interaction(x,y))1.2 add columns
# add identifier based on row numbers
df %>% mutate(id=1:n())
df %>% mutate(id=1:nrow(.))
# row names
rownames(df)
rownames(df) <- LETTERS[1:nrow(df)]
rownames(df)1.2.1 practice
subset the row where (x equals to “a”, y equals to 1) or (x equals to “c”, y equals to 2)
- How many ways to achieve this? you can use
dplyr::filteror[]. - Observe the row names, are they the same before and after subseting?
answer
df %>% filter(z%in%c("a.1","c.2"))
df %>% filter((x=="a"&y==1)|(x=="c"&y==2))
df %>% .[rownames(.)%in%c("A","G"),]
df %>% with(.,.[(x=="a"&y==1)|(x=="c"&y==2),])