简体   繁体   English

使用两个 for 循环和 if 语句在现有数据框中填充新列

[英]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.

相关问题 使用if语句填充数据框 - Populating a dataframe using an if statement 使用 R,根据两个现有列中的值在 dataframe 中创建一个新列 - Using R, create a new column in a dataframe based on the values in two existing columns 使用现有列中的值创建新的数据框列 - Create new dataframe columns using values in an existing column Dataframe中使用条件语句对列求值、计算和新建列 - Using Conditional Statement to Evaluate Column, Calculate, and Create New Colum in Dataframe 新数据框列以现有列为条件 - New dataframe column conditional on existing column 查找在两个数据帧中匹配的两列,并使用 R 将数据帧 2 中的第三列放入数据帧 1 中的新列中 - Find two columns that match in two dataframes and put third column from dataframe 2 into a new column in dataframe 1 using R 是否有用于使用现有数据帧中的两列创建新数据帧的 R 函数? - Is there an R function for creating a new dataframe using two columns from existing dataframe? R:有条件地向现有数据框添加新列 - R : adding a new column to an existing dataframe with a condition 如何编写R函数以从任何两个现有列的条件值在任何数据帧中创建新列? - How to write an R function to create a new column in any dataframe from conditional values of two existing columns? 使用两个现有的 dataframe 创建一个额外的 dataframe - Creating an additional dataframe using two existing dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM