如何将列值转换为百分比

时间:2016-01-11 08:00:24

标签: r

我有一个csv文件如下。

Student Name    English     Evs         Mathematics
                Term 1     Term 1       Term 1  
             Score (150)   Score (150)  Score (150) 
Abhinav.S        107.75    117.25         95.5  
Abhishek.C        112.5    88.75          91    
Aditya              117    116.5          98    

我需要将此转换为百分比而不会干扰数据集,公式为(获得的得分/总得分)* 100。

我尝试了所有可能的方法,但是做不到。有人可以帮助我找到逻辑吗?

2 个答案:

答案 0 :(得分:1)

以下脚本读入输入文件,并创建包含最后三行的数据框,其中包含数字数据。将分数重新缩放到100%比例后,它会创建一个包含更新值的输出文件。输出文件中的格式可能不完全对齐。

all_content = readLines("filein.txt")
temp_content <- all_content[4:6]

dat = read.table(textConnection(temp_content), header = FALSE,
                 stringsAsFactors = FALSE, sep="")

> dat
          V1     V2     V3   V4
1  Abhinav.S 107.75 117.25 95.5
2 Abhishek.C 112.50  88.75 91.0
3     Aditya 117.00 116.50 98.0

dat[1:3, 2:4] <- dat[1:3, 2:4] * (2/3)    # convert to percentage

> dat
          V1       V2       V3       V4
1  Abhinav.S 71.83333 78.16667 63.66667
2 Abhishek.C 75.00000 59.16667 60.66667
3     Aditya 78.00000 77.66667 65.33333

# write out the first three lines to an output file
output <- file("fileout.txt")
writeLines(c(all_content[1], all_content[2], all_content[3]), output)
close(output)

# write out the updated data frame as the last three lines
write.table(dat, file="fileout.txt", append=TRUE, col.names=FALSE,
            row.names=FALSE, quote=FALSE)

答案 1 :(得分:0)

这是一个从文件中提取最高分数的解决方案,您可能需要根据数据格式更改gsub中的正则表达式或读取文件的方式。< / p>

# read fixed width formatted file
test <- read.fwf("test.csv", widths=c(13, 25-13, 39-25, 52-39))

# use first 3 rows as header, convert to character, extract numbers
header <- test[3, 2:4]
header <- lapply(header, as.character)
scores <- as.numeric(gsub("Score \\((.*)\\)", "\\1", header))

# use rest of dataset as data
data <- test[4:nrow(test), ]
data <- as.data.frame(lapply(data, as.character), stringsAsFactors = F)

# divide by max score (you'll might want to do this in a loop/lapply)
data$V2percent <- 100*as.numeric(data$V2)/scores[1]
data$V3percent <- 100*as.numeric(data$V3)/scores[2]
data$V4percent <- 100*as.numeric(data$V4)/scores[3]