R格式数字语法
R format number syntax
我正在尝试将一些数字显示为百分比。
data <- read.csv(
"http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data",
header = FALSE,
na.strings = "?",
strip.white = TRUE
)
colnames(data) <- c("age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "prediction")
colSums(is.na(data))/nrow(data)*100
那里的最后一条命令输出
age workclass fnlwgt education education-num marital-status occupation relationship
0.000000 5.638647 0.000000 0.000000 0.000000 0.000000 5.660146 0.000000
race sex capital-gain capital-loss hours-per-week native-country prediction
0.000000 0.000000 0.000000 0.000000 0.000000 1.790486 0.000000
似乎很难格式化它们,但老实说,我仍然认为 R 是通过黑魔法工作的,所以是否有一些黑魔法可以以相同的方式格式化这些sprintf("%.1f %%", 100*somePercentage)
格式somePercentage
?
希望输出:
age workclass fnlwgt education
0.0% 5.63% 0.0% 0.0%
你可以试试
v2 <- as.numeric(substr(v1, 1,4))
v1[] <- ifelse(v2==0, sprintf('%.1f%%', v2), sprintf('%.2f%%', v2))
v1
# age workclass fnlwgt education education-num
# "0.0%" "5.63%" "0.0%" "0.0%" "0.0%"
# marital-status occupation relationship race sex
# "0.0%" "5.66%" "0.0%" "0.0%" "0.0%"
# capital-gain capital-loss hours-per-week native-country prediction
# "0.0%" "0.0%" "0.0%" "1.79%" "0.0%"
数据
v1 <- colSums(is.na(data))/nrow(data)*100
我正在尝试将一些数字显示为百分比。
data <- read.csv(
"http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data",
header = FALSE,
na.strings = "?",
strip.white = TRUE
)
colnames(data) <- c("age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "prediction")
colSums(is.na(data))/nrow(data)*100
那里的最后一条命令输出
age workclass fnlwgt education education-num marital-status occupation relationship
0.000000 5.638647 0.000000 0.000000 0.000000 0.000000 5.660146 0.000000
race sex capital-gain capital-loss hours-per-week native-country prediction
0.000000 0.000000 0.000000 0.000000 0.000000 1.790486 0.000000
似乎很难格式化它们,但老实说,我仍然认为 R 是通过黑魔法工作的,所以是否有一些黑魔法可以以相同的方式格式化这些sprintf("%.1f %%", 100*somePercentage)
格式somePercentage
?
希望输出:
age workclass fnlwgt education
0.0% 5.63% 0.0% 0.0%
你可以试试
v2 <- as.numeric(substr(v1, 1,4))
v1[] <- ifelse(v2==0, sprintf('%.1f%%', v2), sprintf('%.2f%%', v2))
v1
# age workclass fnlwgt education education-num
# "0.0%" "5.63%" "0.0%" "0.0%" "0.0%"
# marital-status occupation relationship race sex
# "0.0%" "5.66%" "0.0%" "0.0%" "0.0%"
# capital-gain capital-loss hours-per-week native-country prediction
# "0.0%" "0.0%" "0.0%" "1.79%" "0.0%"
数据
v1 <- colSums(is.na(data))/nrow(data)*100