'aggregating data from different column [duplicate]
how do I turn this dataframe
city2001 <- c('a', 'b', 'a')
grade2001 <- c(5, 5, 7)
city2002 <- c('b', 'b', 'a')
grade2002 <- c(8, 9, 10)
df <- data.frame(city2001, grade2001, city2002, grade2002)
into a data frame that looks like this:
| city | grade |
|:---- |:------:|
| a | 5 |
| b | 5 |
| a | 7 |
| b | 8 |
| b | 9 |
| a | 10 |
thanks!
Solution 1:[1]
This is similar to your last question, but not exactly since you are trying to melt the data frame and keep the original values. A similar solution to the previous:
data.frame(
"city"=unlist(df[,grepl("city",colnames(df))]),
"grade"=unlist(df[,grepl("grade",colnames(df))])
)
city grade
city20011 a 5
city20012 b 5
city20013 a 7
city20021 b 8
city20022 b 9
city20023 a 10
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2974951 |
