Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Assign values to a new column based on values of another column where a condition is satisfied

Tags:

dataframe

r

I want to create a new column in a data.frame where its value is equal to the value in another data.frame where a particular condition is satisfied between two columns in each data frame.

The R pseudo-code being something like this:

DF1$Activity <- DF2$Activity where DF2$NAME == DF1$NAME

In each data.frame values for $NAME are unique in the column.

like image 467
gvdb Avatar asked Jan 11 '16 04:01

gvdb


People also ask

How do you change a value in a column in R based on a condition?

Replace column values based on checking logical conditions in R DataFrame is pretty straightforward. All you need to do is select the column vector you wanted to update and use the condition within [] .

How do I assign a value to a new column in R?

To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.

How do I reference a column in R?

We reference a data frame column with the double square bracket "[[]]" operator. For example, to retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].

How do I create a column with the same value in R?

To create a data frame with a column having repeated values, we simply need to use rep function and we can repeat the values in a sequence of the values passed or repeating each value a particular number of times.


3 Answers

without an example its quite hard to tell. But from your description it sounds like a base::merge or dplyr::inner_join operation. Those are quite fast in comparison to if statements.

Cheers

like image 59
sluedtke Avatar answered Oct 23 '22 04:10

sluedtke


Use the ifelse function. Here, I put NA when the condition is not met. However, you may choose any value or values from any vector. Recycling rules1 apply.

DF1$Activity <- ifelse(DF2$NAME == DF1$NAME, DF2$Activity, NA)
like image 44
snaut Avatar answered Oct 23 '22 02:10

snaut


I'm not sure this one actually needs an example. What happens when you create a column with a set of NA values and then assign the required rows with the same logical vector on both sides:

DF1$Activity <- NA
DF1$Activity[DF2$NAME == DF1$NAME] <- DF2$Activity[DF2$NAME == DF1$NAME]
like image 4
IRTFM Avatar answered Oct 23 '22 04:10

IRTFM