Search code examples
rstringconcatenationnumeric

Concatenate string element and number into same cell in dataframe r


If I have this dataframe:

df <- data.frame(col1 = c(NA,NA,NA,"Doggy",NA,NA,"Pound"),col2 = c(1:7))

Let's say I want to check if there is not a NA-value in col1 and add the corresponding number from the other column if that is true, I'd write this:

for (i in 1:nrow(df)){
  if (is.na(df[i,1]) == FALSE){
    #add the df[i,2] number to the df[i,1] string. 
  }

How should I go about concatenating the string with the numeric?


Solution

  • Here df[i,1] <- paste(df[i,1], df[i,2]) will fit.

    for (i in 1:nrow(df)){
      if (is.na(df[i,1]) == FALSE) {
        df[i,1] <- paste(df[i,1], df[i,2])
      }
    }
    df
    #     col1 col2
    #1    <NA>    1
    #2    <NA>    2
    #3    <NA>    3
    #4 Doggy 4    4
    #5    <NA>    5
    #6    <NA>    6
    #7 Pound 7    7
    

    I would do something like:

    i <- which(!is.na(df[,1]))
    df[i,1] <- do.call(paste, df[i,])