【问题标题】:R if row value equals colnames assign 1 else 0 [duplicate]R 如果行值等于 colnames 分配 1 否则 0 [重复]
【发布时间】:2021-05-03 13:11:55
【问题描述】:

原表是这样的:

id food
1 fish
2 egg
2 apple

对于每个 id,其食物的值应为 1 或 0,因此表格应如下所示:

id food fish egg apple
1 fish 1 0 0
2 egg 0 1 0
2 apple 0 0 1

【问题讨论】:

标签: r match row


【解决方案1】:

使用reshape2 包的dcast() 函数的命题:

df1 <- read.table(header = TRUE, text = "
id  food
1   fish
2   egg
2   apple
")

###

df2 <- reshape2::dcast(data = df1, 
                       formula = id+food ~ food, 
                       fun.aggregate = length, 
                       value.var = "food")
df2
#>   id  food apple egg fish
#> 1  1  fish     0   0    1
#> 2  2 apple     1   0    0
#> 3  2   egg     0   1    0

###

df3 <- reshape2::dcast(data = df1, 
                       formula = id+factor(food, levels=unique(food)) ~ 
                                   factor(food, levels=unique(food)), 
                       fun.aggregate = length, 
                       value.var = "food")
names(df3) <- c("id", "food", "fish", "egg", "apple")
df3
#>   id  food fish egg apple
#> 1  1  fish    1   0     0
#> 2  2   egg    0   1     0
#> 3  2 apple    0   0     1

# Created on 2021-01-29 by the reprex package (v0.3.0.9001)

问候,

【讨论】:

  • 嗨,谢谢,我有一个大约 900k 行的数据框,它花费了太多时间
猜你喜欢
  • 2020-05-27
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 2021-09-27
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2017-08-10
相关资源
最近更新 更多