When creating df: for a column only add values in specific rows

Viewed 24

Below simple df example. I'm curious if there is a faster way to create the df$y column.

df <- data.frame(x = c(1:8), y = c("","hello", "world", "", "", "sun", "winter", ""))

  x      y
1 1       
2 2  hello
3 3  world
4 4       
5 5       
6 6    sun
7 7 winter
8 8  

Because I need to add a new column y to a df with 50 rows, but only 15 values on specific rows need to be imputed. Instead of typing a c() with 50 values is it possible to assign only 15 values to a specific row for the new column y?

1 Answers

You can create values in the y column based on values in the x column like this. The first one creates a column of empty stings, and the next two add the strings you want based on the values in the first column.

df$y <- ""
df$y[df$x == 2] <- "hello"
df$y[df$x == 3] <- "world"
Related