Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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?

>Solution :

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         
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading