循环遍历数据帧并匹配R中另一个文件的值
我需要一些关于r的帮助 我有一个数据框:循环遍历数据帧并匹配R中另一个文件的值,r,dataframe,match,R,Dataframe,Match,我需要一些关于r的帮助 我有一个数据框: ant <- data.frame(n_scale = c(0.62, 0.29, -0.9), aa = c('A','B','C')) 然后我读取了一个带有dataframe2的文件,它看起来像: -1 0 1 2 C B A A 我想做到这一点: -1 0 1 2 C B A A -0.9 0.29 0.62 0.
ant <- data.frame(n_scale = c(0.62, 0.29, -0.9),
aa = c('A','B','C'))
然后我读取了一个带有dataframe2的文件,它看起来像:
-1 0 1 2
C B A A
我想做到这一点:
-1 0 1 2
C B A A
-0.9 0.29 0.62 0.62
如何循环通过dataframe2从ant数据框中获取值
非常感谢您的帮助!:) 使用
合并。之后,您可以将结果的hyd
与df2
的匹配
res <- merge(ant, df2)
res <- res[match(df2$hyd, res$hyd), ]
res
# aa n_scale hyd
# 4 C -0.90 -1
# 3 B 0.29 0
# 1 A 0.62 1
# 2 A 0.62 2
res您能为两个数据帧提供dput(df)
吗?您能为每个帧提供dput
的输出吗?两个原因:(1)-1
是一个非标准的列名,通常R会将其更改为类似于X.1
;(2) 同一“列”中的字母和数字意味着所有内容都是字符串。另外,在dataframe2
中是否只有一行?我感觉这只是“合并/连接”(and),但不知怎的,dataframe2以转置状态显示。也许以列格式使用它会更有用,类似于ant
?除非首先转置其中一个数据帧,否则合并不会成功。使用匹配功能会更容易。
res <- merge(ant, df2)
res <- res[match(df2$hyd, res$hyd), ]
res
# aa n_scale hyd
# 4 C -0.90 -1
# 3 B 0.29 0
# 1 A 0.62 1
# 2 A 0.62 2
ant <- data.frame(n_scale = c(0.62, 0.29, -0.9),
aa = c('A','B','C'))
df2 <- data.frame(hyd=c(-1, 0, 1, 2),
aa=c("C", "B", "A", "A"))