简体   繁体   中英

Convert multiple columns to numeric in R and convert asterisks to NA

I have a dataset where some of the data has been redacted for privacy reasons and replaced with asterisks. R reads these columns as characters, but I want it to read the numbers as numbers and convert the asterisks to "NA."

I can easily convert one column at a time like this:

df$colname1 <- as.numeric(as.character(df$colname1))

However, when I try to do many columns at once (starting with column 4), I get issues.

I looked through similar questions on this forum but the solutions did not work for me. If I do this:

df[,4:ncol(df)] <- lapply(df, function(x) as.numeric(as.character(x)))

...then I get two columns which are nothing but NA's.

If I do this:

for(i in c(4:ncol(df))) {
   df[,i] <- as.numeric(as.character(df[,i]));
 }

...then all the columns are nothing but NA's.

Any help would be appreciated. I am a newbie so please explain things simply.

This code will work in changing the columns you want to numeric and then replace all the NA s with 0.

If you want to change all the columns to numeric just use mutate_all() .

library(tidyverse)

df %>% 
  mutate_at(vars(column1), as.numeric)) %>% 
  replace(is.na(.), 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM