Home > database >  Append vector as a data frame column according to another column in the data frame
Append vector as a data frame column according to another column in the data frame

Time:02-03

I have a dataframe.

c1 <- c(3,6,8,2,7)
c2 <- c("S", "", "S", "", "")
df <- data.frame(c1, c2)

I also have a vector

vec <- c(200, 210)

I want to add the values from the vector into a new column in the data frame where there are S values. In rows where no S values are present I just want blank spaces in the new column. The desired output is shown below.

#Output
#   c1 c2 new_column
#1  3  S      200
#2  6    
#3  8  S      210
#4  2    
#5  7   

For my actual data there may be hundreds of rows, many with S values. How can I append this vector in this manner?

CodePudding user response:

Columns in a data frame must have all items the same class. Your vec is class numeric, but a blank "" is class character. You can't mix those in the same column. Missing values NA are a good workaround. I would suggest using NA values instead of blanks in your numeric column as in option_1 below. However, if you really want blanks we can use a character class column as in option_2 below, with the drawback that you won't be able to do math with your numbers because we are treating them as character class not numeric class to mix them with empty strings "".

df$option_1[df$c2 != ""] = vec

df$option_2 = ""
df$option_2[df$c2 != ""] = vec

df
#   c1 c2 option_1 option_2
# 1  3  S      200      200
# 2  6          NA         
# 3  8  S      210      210
# 4  2          NA         
# 5  7          NA         

CodePudding user response:

I think the easiest way to do this would be to filter the initial data frame to entries with an S value, appending the vector, and then joining with the original. The code might be something like:

s_value_df <- df %>% dplyr::filter(c2 == "S")
s_value_df$new_column <- vec
final_df <- dplyr::left_join(df, s_value_df)

This will put NAs where you just have empty strings though so you can replace them after

  •  Tags:  
  • r
  • Related