Neal Barsch
Neal Barsch

Reputation: 2940

R Change Columns with prefix from factor to character

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

Answers (3)

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

You can also do this with ifelse:

df[] <- ifelse(grepl("^ID_", colnames(df)), lapply(df, as.character), df)

Upvotes: 0

any willow brook
any willow brook

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

Gregor Thomas
Gregor Thomas

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

Related Questions