我有一个经常遇到的问题,我需要一种更有效的处理方式。我在下面发布了一个混乱的解决方案。
首先,我将生成一些与我的数据集类似的示例数据。
a <- c(1, 2, 2, 2, 3, 3)
b <- c("10/12", "10/12", "10/12", "10/13", "10/12", "10/12")
c <- c("c", "c", "pv", "c", "c", "c")
data <- matrix(NA, nrow = 6, ncol = 3)
data[,1] <- a
data[,2] <- b
data[,3] <- c
data
[,1] [,2] [,3]
[1,] 1 10/12 c
[2,] 2 10/12 c
[3,] 2 10/12 pv
[4,] 2 10/13 c
[5,] 3 10/12 c
[6,] 3 10/12 c
# [,1] is a unique identifier, [,2] is a date, and [,3] is a type of occurrance
我需要做的是生成一个表,其中每个 ID 每天只包含一个条目,其中有一列显示该条目是否仅对应于“c”、“pv”、“c & pv”或“多个 c” . 数据中不可能有多个 pv
我这样做的方法是使用嵌套的 for 循环:
# I generate an object to post the data to
output.temp <- matrix(NA, nrow = 1, ncol = 4)
# Then I define the outer loop that subsets the data over each ID
ids <- unique(data[,1])
n.ids <- length(ids)
for(i in 1:n.ids){
temp.data <- subset(data, data[,1] == ids[i])
dates <- unique(temp.data[,2])
n.dates <- length(dates)
# Then I define the inner loop that subsets the data for each ID over each date
for(j in 1: n.dates){
date.data <- subset(temp.data, temp.data[,2] == dates[j])
# Then I apply the logic of what to write out
if(nrow(date.data) == 1){
if(date.data[,3] == 'c'){
new.row <- cbind(date.data, "c only")
output.temp <- rbind(output.temp, new.row)
}
if(date.data[,3] == 'pv'){
new.row <- cbind(date.data, "pv only")
output.temp <- rbind(output.temp, new.row)
}
}
if(nrow(date.data) > 1){
if('pv' %in% date.data[,3]){
new.row <- cbind(matrix(date.data[1,], nrow = 1), c("c & pv"))
output.temp <- rbind(output.temp, new.row)
}
else{
new.row <- cbind(matrix(date.data[1,], nrow = 1), " multiple c only")
output.temp <- rbind(output.temp, new.row)
}
}
}
}
# Finally, I drop the unnecessary row and column from the output object
output.final <- output.temp[-1,-3]
这行得通,但效率极低。随着我的数据集变得越来越大(接近 100 万行),它变得越来越成为一个问题。
由于我对R真的很陌生并且对编程几乎没有经验,因此将不胜感激任何有关替代策略的建议。