作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我拼命地试图用数据框中的值填充矩阵。
它是交易数据,所以数据框看起来像这样:
country1 country2 value
1 Afghanistan Albania 30
2 Afghanistan Albania 81
3 Afghanistan China 5
4 Albania Germany 6
5 China Germany 8
6 China Turkey 900
7 Germany Turkey 12
8 Germany USA 3
9 Germany Zambia 700
countries_sorted
[1,] "Afghanistan"
[2,] "Albania"
[3,] "China"
[4,] "Germany"
[5,] "Turkey"
[6,] "USA"
[7,] "Zambia"
Afghanistan Albania China Germany Turkey USA Zambia
Afghanistan NA NA NA NA NA NA NA
Albania NA NA NA NA NA NA NA
China NA NA NA NA NA NA NA
Germany NA NA NA NA NA NA NA
Turkey NA NA NA NA NA NA NA
USA NA NA NA NA NA NA NA
Zambia NA NA NA NA NA NA NA
a<-cast(df, country1~country2 , sum)
> a
country1 Albania China Germany Turkey USA Zambia
1 Afghanistan 111 5 0 0 0 0
2 Albania 0 0 6 0 0 0
3 China 0 0 8 900 0 0
4 Germany 0 0 0 12 3 700
最佳答案
从这两个数据集开始:
#your data.frame
df <- read.table(header=T, file='clipboard', stringsAsFactors = F)
#the list of unique countries
countries <- unique(c(df$country1,df$country2))
#create all the country combinations
newdf <- expand.grid(countries, countries)
#change names
colnames(newdf) <- c('country1', 'country2')
#add a value of 0 for the new combinations (won't affect outcome)
newdf$value <- 0
#row bind with original dataset
df2 <- rbind(df, newdf)
#and create the table using xtabs:
#the aggregate function will create the sum of the value for each combination
> xtabs(value ~ country1 + country2, aggregate(value~country1+country2,df2,sum))
country2
country1 Afghanistan Albania China Germany Turkey USA Zambia
Afghanistan 0 111 5 0 0 0 0
Albania 0 0 0 6 0 0 0
China 0 0 0 8 900 0 0
Germany 0 0 0 0 12 3 700
Turkey 0 0 0 0 0 0 0
USA 0 0 0 0 0 0 0
Zambia 0 0 0 0 0 0 0
关于r - 如何用数据框值填充空矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32735515/
我是一名优秀的程序员,十分优秀!