Reputation: 2940
I have a data frame with factors and characters. I want to change the columns with the column prefix "ID_" to be changed from factors to characters.
I tried the below, but it changes the whole data frame to characters, I just want to change the colnames with "ID_". I don't know how many "ID_" will end up in the data frame (this is part of a larger function that will loop across dataframes with various numbers of "ID_")
###Changes the whole dataframe to character rather than only the intended columns
df.loc[] <- lapply(df.loc[, grepl("ID_", colnames(df.loc))], as.character)
Upvotes: 0
Views: 967
Reputation: 9656
You can also do this with ifelse
:
df[] <- ifelse(grepl("^ID_", colnames(df)), lapply(df, as.character), df)
Upvotes: 0
Reputation: 68
Here is a tidyverse solution:
food <- data_frame(
"ID_fruits" = factor(c("apple", "banana", "cherry")),
"vegetables" = factor(c("asparagus", "broccoli", "cabbage")),
"ID_drinks" = factor(c("absinthe", "beer", "cassis"))
)
food %>%
mutate_at(vars(starts_with("ID_")), as.character)
```
Upvotes: 3
Reputation: 145965
The problem is you assign to the whole data frame with df.loc[] <-
. Try this:
my_cols <- grepl("ID_", colnames(df.loc))
df.loc[my_cols] <- lapply(df.loc[my_cols], as.character)
Upvotes: 6