Chetan Arvind Patil Chetan Arvind Patil - 1 year ago 50
R Question

Adding Value To New Cell If Parameter Match For Other Cell

I have created a new empty column in a

data.frame
data
:

data$new_column <- 0


Above value will be updated after comparing all rows based on a certain condition. Pseudo code would be like:

if ( data$column_x == X & data$column_y == Y ){
data$new_column <- "New Data" # Only one cell should be update based on row & column ID
}


I am not sure how I can update other column based on the condition of two different column. I tried extracting
row
ID, and based on that tried updating new column, but it's not working out:

row_id <- which(data$column_x == X & data$column_y == Y)
data[row_id, data$new_column ] <- "New Data"


Sample Data

column_x column_y new_column
-34 12 0
-36 20 0
-36 12 0
-34 18 0
-34 10 0
-35 24 0
-35 16 0
-33 22 0
-33 14 0
-35 22 0


Can anyone please suggest correct approach for this? Thanks.

Answer Source

You can do this:

data <- data.frame(column_x = c(-34, -36, -36, -34, -34, -35, -35, -33, -33, -35), column_y = c(12, 20, 12, 18, 10, 24, 16, 22, 14, 22), new_column = 0)

data$new_column[data$column_x == -36 & data$column_y == 12] <- 123

data

   column_x column_y new_column
1       -34       12          0
2       -36       20          0
3       -36       12        123
4       -34       18          0
5       -34       10          0
6       -35       24          0
7       -35       16          0
8       -33       22          0
9       -33       14          0
10      -35       22          0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download