假设我有一个键值对列表:
l <- list("A" = 10, "B" = 20, "C" = 30)
以及一个包含值向量和相应类型向量的数据框:
df <- data.frame (type=c("A","A","B","B","B","C"),value=c(1,2,3,4,5,6))
df
type value
1 A 1
2 A 2
3 B 3
4 B 4
5 B 5
6 C 6
我想根据列表中这些值的类型值来划分这些值,这样我最终会得到一个如下所示的数据框:
df
type value newval
1 A 1 0.10
2 A 2 0.20
3 B 3 0.15
4 B 4 0.20
5 B 5 0.25
6 C 6 0.20
我怀疑这很容易,但谷歌让我失望了,我已经费尽心思试图弄清楚这一点。在我更熟悉的 python 中,我可以迭代行并为我的列表使用字典,但如何做到这一点也不明显,而且在 R 中似乎也不合适。
最佳答案
如果您考虑一下加入或合并的条款,它就会变得很简单。
请注意,我假设值是数字,而不是您示例中的字符。
我喜欢data.table
,因此将展示一种使用该包来执行此操作的方法
library(data.table)
# df with value as numeric
df <- data.frame (type=c("A","A","B","B","B","C"),value=1:6)
# create the data.table
DT <- data.table(df, key = 'type')
# create the key-value list as a data.table (specifying the levels the same
# as in DT[,type]
byl <- data.table(type = factor(names(l), levels = levels(DT[,type])), value = unlist(l), key = 'type')
# note they are both keyed by type, so we can join by type and then
# create a column that is value/ (value in the i component)
# so we use value / i.value
# i.value references value from the i argument (byl in this case)
DT[byl, newval := value / i.value ]
# look in DT now
DT
type value newval
1: A 1 0.10
2: A 2 0.20
3: B 3 0.15
4: B 4 0.20
5: B 5 0.25
6: C 6 0.20
关于r - 基于 2 列数据框和键值列表添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13618375/