簡體   English   中英

添加基於 2 列數據框和鍵值列表的列

[英]Adding column based on 2 columns of data frame and a key-value list

假設我有一個鍵值對列表,如下所示:

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 中,我可以遍歷行並為我的列表使用 dict,但是如何做到這一點也不明顯,在 R 中似乎也不合適。

如果您考慮加入或合並的條款,它就會變得直截了當。

請注意,我認為值是數字,而不是您的示例中的字符。

我喜歡data.table所以將展示一種使用該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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM