[英]Using two for loops and if statement for populating a new column in an existing dataframe
I am trying to "fill" a column of a dataset by combining information by two other columns.我试图通过组合其他两列的信息来“填充”数据集的一列。 More specifically, I am trying the following:
更具体地说,我正在尝试以下操作:
a <- data.frame(gender_p1 = c("man", "woman","man","man"), gender_p2 = c("man", "man","woman","woman"), couple = c(""))
> a
gender_p1 gender_p2 couple
1 man man
2 woman man
3 man woman
4 man woman
I want to iterate through a[1] and a[2] to populate respectively a[3] column.我想遍历 a[1] 和 a[2] 以分别填充 a[3] 列。 I tried to use a double for loop and an ifelse statement within, without any success.
我尝试在其中使用 double for 循环和 ifelse 语句,但没有成功。 Is there any better approach for it?
有没有更好的方法呢? Thanks in advance for any possible proposal.
在此先感谢您提供任何可能的建议。
If your data has not super many rows, check out dplyr
(or the tidyverse
in general).如果您的数据行数
dplyr
,请查看dplyr
(或一般的tidyverse
)。 You can use mutate
to create new columns based on some conditions:您可以使用
mutate
根据某些条件创建新列:
a <- data.frame(gender_p1 = c("man", "woman","man","man"), gender_p2 = c("man", "man","woman","woman"))
library(dplyr)
a <- a %>%
mutate(same_sex = if_else(
gender_p1 == gender_p2,
TRUE,
FALSE
))
a
gender_p1 gender_p2 same_sex
1 man man TRUE
2 woman man FALSE
3 man woman FALSE
4 man woman FALSE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.