我有一个参考表:
ref <- data.frame("Strong"=c("A","A","B","B","C","C","D"),
"Medium"=c("A","B","B","C","C","D","D"),
"Moderate"=c("B","C","C","C","D","D","D"),
"Weak"=c("C","C","D","D","D","D","D"))
rownames(ref) <- c("WS1","WS2","WS3","WS4","WS5","WS6","WS7")
还有一个大的dataframe
(如下所示):
df <- data.frame("Rad"=c("Weak","Weak","Weak","Moderate","Moderate"), "Wind"=c("WS4","WS3","WS3","WS2","WS4"))
我需要在参考表Wind
中从Rad
中查找df
和ref
值。为此,我使用以下代码检索索引,然后使用这些索引值从ref
复制值:
df$x <- apply(df,1,function(x){which(colnames(ref) == df[x,"Rad"])})
df$x <- apply(df,1,function(x){which(colnames(ref) == x$Rad)})
df$y <- apply(df,1,function(x){which(rownames(ref) == df[x,"Wind"])})
df$y <- apply(df,1,function(x){which(rownames(ref) == x$Wind)})
预期输出如下:
Rad Wind PG
1 Weak WS4 D
2 Weak WS3 D
3 Weak WS3 D
4 Moderate WS2 C
5 Moderate WS4 C
上面的代码有效,但是存在问题:
答案 0 :(得分:2)
使用data.table
的另一种方法。即使在大型数据集上,Shuld都能快速运行。
使用与@IceCreamToucan解决方案相同的逻辑,但是停留在data.table
之内。
解释:使用熔化的ref
表,对df
执行更新联接。
library( data.table )
setDT(df)[ melt( setDT( ref, keep.rownames = TRUE ), id.vars = "rn" ),
PG := i.value,
on = .( Wind == rn, Rad == variable )][]
# Rad Wind PG
# 1: Weak WS4 D
# 2: Weak WS3 D
# 3: Weak WS3 D
# 4: Moderate WS2 C
# 5: Moderate WS4 C
答案 1 :(得分:1)
我们可以分别用match
和rownames
列以及colnames
的子集中{{1}的ref
RAD
和WIND
。
ref
答案 2 :(得分:1)
library(tidyverse)
library(data.table) # for melt
ref_long <-
ref %>%
rownames_to_column('row') %>%
melt('row')
df %>%
left_join(ref_long, by = c('Rad' = 'variable', 'Wind' = 'row'))
# Rad Wind value
# 1 Weak WS4 D
# 2 Weak WS3 D
# 3 Weak WS3 D
# 4 Moderate WS2 C
# 5 Moderate WS4 C