2

我有数据框

names <- c("doe.jane", "doe.john", "smith.bob")
number <- c(3, 5, 1)
site <- c("A1", "A1", "A2")
df <- as.data.frame(matrix(c(site, names, number), 3))
names(df) <- c("site", "names", "number")

我只需要用姓氏替换全名,然后折叠数据框,因此输出为

names <- c("doe", "smith")
number <- c(8, 1)
site <- c("A1", "A2")
df <- as.data.frame(matrix(c(site, names, number), 2))
names(df) <- c("site", "names", "number")
4

2 回答 2

3

你想做这样的事情:

last.names <- function(names) {
    names <- as.character(names)
    split.names <- strsplit(names, split='.', fixed=TRUE)
    sapply(split.names, function(x) x[1])
}

df <- within(df, names <- last.names(names))
df <- with(df, aggregate(as.numeric(number), by=list(site=site, names=names), sum))

我会指出你的定义df有点误导。你真的只需要说df <- data.frame(names, number, site)。你这样做的方式导致结果中的三factordata.frame

于 2012-06-24T18:40:27.627 回答
1

这是一个使用正则表达式来获取名称部分的版本。由于将数字保存为因子,我重新创建了数据 - 感谢 mplourde 指出这一点。

#set up the data
names <- c("doe.jane","doe.john","smith.bob")
number <- c(3,5,1)
site <- c("A1","A1","A2")
df <- data.frame(site,names,number)

#get the first part of the name
df$names <- gsub("([[:alpha:]]+)\\.([[:alpha:]]+)","\\1",df$names)
#aggregate the data by site and name
dfnew <- aggregate(df["number"],df[c("site","names")],sum)

> dfnew
  site names number
1   A1   doe      8
2   A2 smith      1
于 2012-06-24T23:06:21.963 回答