R中的数据框列替换和摘要

时间:2012-06-24 18:21:26

标签: r dataframe

我有数据框

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")

2 个答案:

答案 0 :(得分: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)。这样做会导致生成factor中的三个data.frame列。

答案 1 :(得分: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