jeudi 5 juillet 2018

Mutate column into separate data frame using a condition on length

I would like to add new columns with mutate using a condition. If the length of the variable is zero, then add a dash in the column, otherwise add the content. This is part of a loop where I bind the resulting data frames, hence all lists have only one item and the data frames here only have one row.

I tried solving this using tips I found here: Combine mutate with conditional values

Example code:

x <- "bbb"
y <- ""
end <- data.frame("aaa")

end <- x %>%
mutate (end, x_col = case_when(length()==0 ~ '-',
                         length()!=0 ~ .))

end <- y %>%
mutate (end, y_col = case_when(length()==0 ~ '-',
                         length()!=0 ~ .))

With both, I get this: "Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "character""

Aucun commentaire:

Enregistrer un commentaire