[英]In R, how do I match values from selected rows in one data frame with selected columns in another?
I have two separate dataframes.我有两个单独的数据框。 A few of the columns from one dataframe have the same name as some rows in the other.
一个数据框中的一些列与另一个数据框中的某些行具有相同的名称。 How can I match values corresponding to a few rows in one df to values corresponding to a few columns (with the same names as the rows) in another df?
如何将对应于一个 df 中几行的值与对应于另一个 df 中几列(与行同名)的值匹配?
In this example, I want to know if for each row in the first df, the values (A/B/C/D) under each question (E4Q_) matches the value at row E4Q_ and column 'Answer' in df2.在此示例中,我想知道对于第一个 df 中的每一行,每个问题 (E4Q_) 下的值 (A/B/C/D) 是否与 df2 中 E4Q_ 行和“Answer”列的值匹配。 After this, I want to either print TRUE/FALSE or 1/0 in a third data frame which is set up like the first.
在此之后,我想在第三个数据框中打印 TRUE/FALSE 或 1/0,该数据框中的设置与第一个类似。
df1:
Name E4Q1 E4Q2 E4Q3 E4Q4 E4Q5
XYZ B B A A B
DEF D D D C B
GHJ - - B A C
df2:
Question Answer
E4Q1 B
E4Q2 D
E4Q3 C
E4Q4 A
E4Q5 C
df3:
Name E4Q1 E4Q2 E4Q3 E4Q4 E4Q5
XYZ 1 0 0 1 0
DEF 0 1 0 0 0
GHJ 0 0 0 1 1
If you are using the current version of R you have stringsAsFactos=FALSE as the default.如果您使用的是 R 的当前版本,则默认使用 stringsAsFactos=FALSE。 This task is an excellent example of why that change was made.
这个任务是一个很好的例子,说明为什么要做出改变。 Factos would complicate this process completely.
Factos 会使这个过程完全复杂化。 If you are like me you need to do the data entry with that explicitly set:
如果您像我一样,则需要使用明确设置的数据输入:
df1 <- read.table(text= "Name E4Q1 E4Q2 E4Q3 E4Q4 E4Q5
XYZ B B A A B
DEF D D D C B
GHJ - - B A C", head=TRUE,stringsAsFactors=FALSE)
df2 <- read.table(text=" Question Answer
E4Q1 B
E4Q2 D
E4Q3 C
E4Q4 A
E4Q5 C", head=TRUE,stringsAsFactors=FALSE)
df3 <- df1 # same structure but Question columns will be changed to 1/0
First try : loop through col names and compare results to correct values in df2:首先尝试:遍历列名称并将结果与 df2 中的正确值进行比较:
for( i in names(df1[-1]) ){ df3[[i]] <- df1[[i]] == df2[df2$Question==i, 2] }
df3
Name E4Q1 E4Q2 E4Q3 E4Q4 E4Q5
1 XYZ TRUE FALSE FALSE TRUE FALSE
2 DEF FALSE TRUE FALSE FALSE FALSE
3 GHJ FALSE FALSE FALSE TRUE TRUE
So need to coerce to numeric, either with as.numeric or by adding 0.所以需要强制转换为数字,要么使用 as.numeric 要么添加 0。
for( i in names(df1[-1]) ){ df3[[i]] <- ( df1[[i]] == df2[df2$Question==i, 2])+0 }
df3
Name E4Q1 E4Q2 E4Q3 E4Q4 E4Q5
1 XYZ 1 0 0 1 0
2 DEF 0 1 0 0 0
3 GHJ 0 0 0 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.