[英]How to convert all columns of a df from characters to numeric?
我想將df的所有列從字符轉換為數字。
df示例:
A B C D
"1" "10.2" "0.2" "8"
"5" "2.1" "0.5" "6"
"3" "4.6" "0.3" "7"
將所有列(A,B,C,D)中的字符值轉換為數字。 謝謝!
有很多方法可以做到這一點。 我喜歡purrr
這種方法
library(purrr)
df %>% map_if(is.character, as.numeric)
str(df)
'data.frame': 3 obs. of 4 variables:
$ A: num 1 5 3
$ B: num 10.2 2.1 4.6
$ C: num 0.2 0.5 0.3
$ D: num 8 6 7
我們可以使用lapply
df[] <- lapply(df, function(x) if(is.character(x)) as.numeric(x)
else x)
如果我們知道所有列都是“字符”並且需要轉換
df[] <- lapply(df, as.numeric)
看看: R將帶引號的數字轉換為數字
基本上,您可以將apply()
函數與as.numeric()
以將數字從字符串轉換為數字。
我喜歡這樣。
data <- apply(df, 1, fun(x) as.numeric(x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.