1

Some sample code to get started here

ST <- c("AL","AL","AK","AK") 
X1 <- c("2,21", "2,29", "3,49", "2.3") 
X2 <- c("10,333","10,333", "11,333", "11,333") 
df <- cbind(ST, X1, X2) 

I am trying to write a loop, either with a for loop or with lapply that can parse out the numbers but skip the first row with state names. So far I am stuck with:

  for(i in seq_along(df[,-1]))  {
  df[[i]] <- parse_number(df[[i]])
  } 

This is producing NA's in the ST column. I'm sure there is a simple fix to this, but it escapes me. Thank you!

Aaron
  • 109
  • 5

1 Answers1

2

You may try below, You can avoid for loop by using lapply/sapply here, lapply or sapply can iterate column wise:

ST <- c("AL","AL","AK","AK") 
X1 <- c("2,21", "2,29", "3,49", "2.3") 
X2 <- c("10,333","10,333", "11,333", "11,333") 
df <- data.frame(ST,X1, X2)

df[,-1] <- lapply(df[,-1] , readr::parse_number)

Note: I am using parse_number from readr here. Your parse_number function is not mentioned , hence I assumed its the one from readr.

Output:

#  ST    X1    X2
#1 AL 221.0 10333
#2 AL 229.0 10333
#3 AK 349.0 11333
#4 AK   2.3 11333
PKumar
  • 10,971
  • 6
  • 37
  • 52