How To Assign A Column Value In A Data Frame Based On Another ...
Maybe your like
To assign a column value based on another column, we can use ifelse function. The ifelse function checks whether the value in one column of one data frame matches the value in another column of another data frame by using equal sign (==) and then replace the original value with the new column if there is no match else returns the original value. Check out the below example to understand how it can be done.
Example
Consider the below data frame −
Live Demo
> x1<-rpois(20,2) > x2<-rpois(20,5) > df1<-data.frame(x1,x2) > df1Output
x1 x2 1 3 5 2 3 7 3 0 6 4 0 5 5 4 6 6 3 8 7 1 5 8 0 8 9 4 6 10 1 2 11 2 3 12 2 6 13 0 0 14 1 9 15 0 0 16 4 2 17 3 5 18 3 8 19 1 3 20 2 7Example
Live Demo
> y1<-rpois(20,2) > y2<-rpois(20,5) > df2<-data.frame(y1,y2) > df2Output
y1 y2 1 3 8 2 4 11 3 3 8 4 2 2 5 1 3 6 1 4 7 1 7 8 1 2 9 5 2 10 2 4 11 2 3 12 1 3 13 1 5 14 3 4 15 0 3 16 2 5 17 3 5 18 1 7 19 5 10 20 2 6Replacing values in x1 of df1, if x2 of df1 is same as y2 of df2 otherwise returning x1 in df1 −
> df1$x1<-ifelse(df1$x2==df2$y2,df2$y2,df1$x1) > df1Output
x1 x2 1 3 5 2 3 7 3 0 6 4 0 5 5 4 6 6 3 8 7 1 5 8 0 8 9 4 6 10 1 2 11 3 3 12 2 6 13 0 0 14 1 9 15 0 0 16 4 2 17 5 5 18 3 8 19 1 3 20 2 7Tag » Add Column From One Dataframe To Another Based On Condition R
-
Add A New Column To A Dataframe Using Matching Values Of Another ...
-
R: Add A Column To Dataframe Based On Other Columns With Dplyr
-
How To Add A Column To A Dataframe In R With Tibble & Dplyr
-
Add New Column In Dataframe Based On Condition From Another ...
-
4 Data Wrangling Tasks In R For Advanced Beginners - Computerworld
-
Add A Column In A Pandas DataFrame Based On An If-Else Condition
-
How To Insert A New Column Based On Condition In Python?
-
How To Add A Column Based On Other Columns In R DataFrame
-
How To Add Column From Another DataFrame In Pandas
-
R: How To Add Column To Data Frame Based On Other Columns
-
How To Add A Column To A DataFrame In Python Pandas
-
Replace Values In Data Frame Conditionally In R (4 Examples)
-
Select Rows In DataFrame By Conditions On Multiple Columns
-
Joining Pandas Dataframes - Data Carpentry