R: convert list of numbers from character to numeric

前端 未结 3 1020
旧巷少年郎
旧巷少年郎 2021-01-24 22:17

I have a column in my dataframe where in every cell there are one or more numbers. If there are many numbers, they are seperated with a space. Furthermore, R considers them as a

3条回答
  •  佛祖请我去吃肉
    2021-01-24 22:49

    Here are two more options which work correctly on a vector (it seems)

    str1 <- c("6 310 21 20 64", "6 310 21 20 64","6 310 21 20 64")
    rowSums(read.table(text = str1))
    ## [1] 421 421 421
    

    Or using data.table::fread

    rowSums(data.table::fread(paste(str1, collapse = "\n")))
    # [1] 421 421 421        
    

    Or as mentioned in comments by @akrun, you can use Reduce(`+`,...) instead of rowSums(...) in both cases in order to avoid to marix conversion

提交回复
热议问题