简体   繁体   中英

R For Loop for converting character to numeric

Using R. I have a data set that has a "messy" character variable. I need to clean this variable by removing any characters that are not numbers and then converting it to a numeric variable using a for loop.
Here is my for loop.

s = messy$SETTLEMENT
n = length(s)
for(i in 1:n){
  // Complete the code that cleans each element of s, s[i], using gsub.
  s = gsub("[^[:digit:]]", "", s)
  as.numeric(s)
  
}

I am able to clean the variable but s does not return as a numeric variable. Please help.

在此处输入图像描述

You can use readr::parse_number(text_to_be_converted_into_number) .

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