我正在尝试将原始数据从文本文件转换为矩阵。我已经使用 读取了数据readLines()
,然后将数据与grepl()
(iemale;20;30.5 => "male" "20" "30.5") 分隔到一个列表中。
唯一的问题是数据丢失了一些没有记录性别、年龄或体重的值,或者逗号代替了小数点。在这些情况下,数据列表包含如下所示的行:
##"male" "20" "55.3"
##"male" "45"
或者
##"" "55" "55"
我想通过附加一个函数来更正这些实例NA
。然后将该函数应用于lapply(data.dataList, function)
. R中的函数不是我的强项,但这是我的第一次尝试:
# function to correct column order for weight data
f.assignFields <- function(x) {
# create a blank character vector of length 3
out <- character(3)
sex <- grepl("[[:alpha:]]",x)
out[1] <- x[sex]
age.num <- which(as.numeric(x) <0)
out[2] <- ifelse(length(length(age.num) > 0, x[age.num], NA)
weight.num <- which(as.numeric(x) > 0)
out[3] <- ifelse(length(weight.num) > 0, x[weight.num], NA)
out
}
data.standardFields <- lapply(data.dataList, fassignFields)
我知道我想把带字母的字符串放在第一列,把其他的放在第二和第四列。我也应该将“,”替换为“。” 申请之前或之后的权重lapply()
?只需向正确的方向轻推一点,将不胜感激。
编辑:从文本文件中提取的数据非常小。只有九个人记录了他们的性别、年龄和体重。练习的重点是通过修改和转换数据来处理原始数据,以检查自己修改数据的有用性,而不是使用read.table()
.
male;28;81.3
male;45;
female; 17 ;57,2
female;64;62.8
male;16;55.3
male;;50,1
female;20.4;55
female;;
;55;55
这是我所做的:
#read text file
weight.data <- readLines(text.txt)
#removed white spaces
weight.data <- gsub(" ","",weight.data)
weight.data
[1] "male;28;81.3"
[2] "male;45;"
[3] "female;17;57,2"
[4] "female;64;62.8"
[5] "male;16;55.3"
[6] "male;;50,1"
[7] "female;20.4;55"
[8] "female;;"
[9] ";55;55"
#split strings by semicolon
weight.dataList <-strsplit(weight.data, split = ";")
weight.dataList
[[1]]
[1] "male" "28" "81.3"
[[2]]
[1] "male" "45"
[[3]]
[1] "female" "17" "57,2"
[[4]]
[1] "female" "64" "62.8"
[[5]]
[1] "male" "16" "55.3"
[[6]]
[1] "male" "" "50,1"
[[7]]
[1] "female" "20.4" "55"
[[8]]
[1] "female" ""
[[9]]
[1] "" "55" "55"
我想将 NA 添加到丢失的行中。我正在尝试创建一个函数来纠正该字段的行尺寸。例如,第二个条目的权重应该是 NA。
# function to correct column order and size for weight data
f.assignFields <- function(x) {
# create a blank character vector of length 3
out <- character(3)
sex <- grepl("[[:alpha:]]",x)
# puts sex in first column
out[1] <- x[sex]
# assigns NA if age missing
age.num <- which(as.numeric(x) <0)
out[2] <- ifelse(length(length(age.num) > 0, x[age.num], NA)
# assigns NA if weight missing
weight.num <- which(as.numeric(x) > 0)
out[3] <- ifelse(length(weight.num) > 0, x[weight.num], NA)
out
}
data.standardFields <- lapply(data.dataList, fassignFields)
最后,我将使用unlist()
andmatrix()
将数据转换为行列格式。我想用 NA 替换数据的缺失值,将数据按以下顺序“性别、年龄、体重”并固定权重,使 55,1 显示为 55.1。