简体   繁体   English

R 中有没有办法创建一个新列,以其他列为条件分配值?

[英]Is there a way in R to create a new column, assigning values conditional on other columns?

I have a data frame with multiples dates and associated data/variables.我有一个包含多个日期和相关数据/变量的数据框。 I'm looking to create a new column in the data frame that assigns a Yes or No variable to the new column depending on the date of the other column.我希望在数据框中创建一个新列,该列根据另一列的日期将 Yes 或 No 变量分配给新列。 For example, all dates before, say, Date1 need a 'Yes' in the new column, and all dates after Date1 need a 'No' in the new column.例如,比方说,Date1 之前的所有日期在新列中都需要一个“是”,而 Date1 之后的所有日期在新列中都需要一个“否”。 How do I do this?我该怎么做呢?

The simplest way to add a new column based on a binary test is with the base R ifelse function.基于二进制测试添加新列的最简单方法是使用基本的 R ifelse函数。 Here's an example using mtcars and testing for mpg >= 25 with the new columns test and test2 added to the dataframe.这是一个使用 mtcars 并测试 mpg >= 25 的示例,并将新列testtest2添加到数据框中。 test2 illustrates creating a new binary column as type logical: test2说明了创建一个新的二进制列作为逻辑类型:

cars <- mtcars
cars$test <- ifelse(cars$mpg >= 25, "Yes", "No")
cars$test2 <- ifelse(cars$mpg >= 25, TRUE, FALSE)
head(cars, 5)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb test test2
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4   No FALSE
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4   No FALSE
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1   No FALSE
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1   No FALSE
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2   No FALSE

You can use the logical comparison operators on Date values.您可以对日期值使用逻辑比较运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM