【问题标题】:Create multiple columns of values that are in second column and fill new data frame with number of occurences according to first column [duplicate]创建第二列中的多列值,并根据第一列用出现次数填充新数据框[重复]
【发布时间】:2018-05-26 12:14:35
【问题描述】:

我是堆栈溢出的新手,如果我没有正确提问,我很抱歉。 我有两列 countryYear

    INDIA 1970
    USA   1970
    USA   1971
    INDIA 1970
    .
    .
    UK    1972

我想要这样的新数据框,我需要用事件填充它。

            1970 1971 1972.... 
    INDIA    2
    USA      1     1
    UK                1

【问题讨论】:

标签: r


【解决方案1】:

一个选项可以是使用reshape2::dcastfun.aggregate 参数设置为length

library(reshape2)
dcast(df, Country~Year, length)
#   Country 1970 1971 1972
# 1   INDIA    2    0    0
# 2      UK    0    0    1
# 3     USA    1    1    0

数据:

df <- read.table(text = 
"Country Year
INDIA 1970
USA   1970
USA   1971
INDIA 1970
UK    1972",
header = TRUE, stringsAsFactors = FALSE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多