【发布时间】:2019-04-17 20:52:00
【问题描述】:
我有一个数据框,其中包含 10 列数据(温度、湿度值等)。 R 将它们标识为字符串。我使用以下命令将其中一列转换为数字格式:
df$temp_out = as.numeric(df$temp_out)
问题是我还有另外 7 列也需要转换。我可以为每个人都做,但我需要在大约 50 df 内完成,所以有点不方便。欢迎任何帮助!
【问题讨论】:
标签: r dataframe type-conversion numeric
我有一个数据框,其中包含 10 列数据(温度、湿度值等)。 R 将它们标识为字符串。我使用以下命令将其中一列转换为数字格式:
df$temp_out = as.numeric(df$temp_out)
问题是我还有另外 7 列也需要转换。我可以为每个人都做,但我需要在大约 50 df 内完成,所以有点不方便。欢迎任何帮助!
【问题讨论】:
标签: r dataframe type-conversion numeric
我们可以使用lapply遍历列并应用as.numeric
df[cols] <- lapply(df[cols], as.numeric)
在哪里
cols <- names(df)[4:10] # or column index (change the index if needed)
【讨论】:
如果您喜欢使用 dplyr,另一种选择是使用 mutate_if():
df %>% mutate_if(is.character,as.numeric)
【讨论】:
使用 tidyverse 只转换数字列:
df <- df %>% mutate_if(is.numeric, as.numeric)
【讨论】:
将字符数据框列更改为具有多列的 r 中的数字
df[, 4:17] <- lapply(df[, 4:17], as.numeric)
【讨论】: