cbind 1:nrows将相同ID变量值写入原始data.frame
我有一个大的数据帧,其中一个变量id(第一列)在第二列中以不同的值递归。我的想法是对数据帧进行排序,将其拆分为一个列表,然后使用一个函数将序列1:nrows(变量id)绑定到每个组。到目前为止,我的代码是:cbind 1:nrows将相同ID变量值写入原始data.frame,r,ggplot2,dataframe,lapply,splitstackshape,R,Ggplot2,Dataframe,Lapply,Splitstackshape,我有一个大的数据帧,其中一个变量id(第一列)在第二列中以不同的值递归。我的想法是对数据帧进行排序,将其拆分为一个列表,然后使用一个函数将序列1:nrows(变量id)绑定到每个组。到目前为止,我的代码是: DF <- DF[order(DF[,1]),] DF <- split(DF,DF[,1]) DF <- lapply(1:length(DF), function(i) cbind(DF[[i]], 1:length(DF[[i]]))) ……等等 这是我的代码: c
DF <- DF[order(DF[,1]),]
DF <- split(DF,DF[,1])
DF <- lapply(1:length(DF), function(i) cbind(DF[[i]], 1:length(DF[[i]])))
……等等
这是我的代码:
cell.areas.t <- function(file) {
dat = paste(file)
DF <- read.table(dat, col.names = c("cell","area"))
DF <- splitstackshape::getanID(DF, "cell")[] # thanks to akrun's answer
ggplot2::ggplot(data = DF, aes(x = .id , y = area, color = cell)) +
geom_line(aes(group = cell)) + geom_point(size=0.1)
}
有一种更简单的方法来实现这个目标。将
ave
与seq.int
DF$group_seq <- ave(DF, DF[,1], FUN=function(x){ seq.int(nrow(x)) } )
DF$group_seq我们可以使用getanID
fromsplitstackshape
library(splitstackshape)
getanID(DF, "cell")[]
这太棒了!非常感谢。实际上给了我两个额外的列(groupseq.cell
,groupseq.area
),但这不是什么大问题,也很好<代码>DF
DF$.id[DF$cell != temporary.cellindex] <- max(DF$.id[DF$cell != temporary.cellindex])
cell.areas.t <- function(file) {
dat = paste(file)
DF <- read.table(dat, col.names = c("cell","area"))
DF$.id <- c(0, cumsum(diff(DF$cell) < 0)) + 1L # Indexing
title <- getwd()
myplot <- ggplot2::ggplot(data = DF, aes(x = .id , y = area, color = factor(cell))) +
geom_line(aes(group = cell)) + geom_line(size=0.1) + theme(legend.position="none") + ggtitle(title)
#save the plot
image=myplot
ggsave(file="cell_areas_time.svg", plot=image, width=10, height=8)
}
DF$group_seq <- ave(DF, DF[,1], FUN=function(x){ seq.int(nrow(x)) } )
library(splitstackshape)
getanID(DF, "cell")[]