在R中减少data.frame的行并扩展列
我把这个数据框用R表示在R中减少data.frame的行并扩展列,r,dataframe,R,Dataframe,我把这个数据框用R表示 > a <- data.frame(year = c(2001,2001,2001,2001), country = c("Japan", "Japan","US","US"), type = c("a","b","a","b"), amount = c(35,67,39,45)) > a year country type amount 1 2001 Japan a 35 2 2001 Japan b 67 3
> a <- data.frame(year = c(2001,2001,2001,2001), country = c("Japan", "Japan","US","US"), type = c("a","b","a","b"), amount = c(35,67,39,45))
> a
year country type amount
1 2001 Japan a 35
2 2001 Japan b 67
3 2001 US a 39
4 2001 US b 45
基本上,我希望行数是(年份x国家/地区)对数,并且我希望为每种类型创建额外的列。基本解决方案,但需要重命名列和行
reshape(a, v.names="amount", timevar="type", idvar="country", direction="wide")
year country amount.a amount.b
1 2001 Japan 35 67
3 2001 US 39 45
重塑溶液
library(reshape2)
dcast(a, year+country ~ paste("type", type, sep="."), value.var="amount")
year country type.a type.b
1 2001 Japan 35 67
2 2001 US 39 45
另一种方法是在
tidyr
包中使用spread
,在dplyr
包中使用rename
,以交付预期结果
library(dplyr)
library(tidyr)
spread(a,type, amount) %>%
rename(type.a = a, type.b = b)
# year country type.a type.b
#1 2001 Japan 35 67
#2 2001 US 39 45
library(dplyr)
library(tidyr)
spread(a,type, amount) %>%
rename(type.a = a, type.b = b)
# year country type.a type.b
#1 2001 Japan 35 67
#2 2001 US 39 45