Llopis提出的要求是,如果一个给定的ID在某一列上有不同的信息,则保留两行,这使得问题更加复杂。首先,让我们创建一些示例数据,以说明这种情况:
b <- read.table(text = "ID Age Steatosis Mallory Lille_dico Lille_3 Bili.AHHS2cat
HA-09 16 <NA> <NA> <NA> 5 NA
HA-09 16 <33% no/occasional <NA> NA 1
HA-10 20 no <NA> <NA> 2 NA
HA-10 20 yes <NA> 0 NA NA",
na.strings = c("NA", "<NA>"), header = T)
ID Age Steatosis Mallory Lille_dico Lille_3 Bili.AHHS2cat
1 HA-09 16 <NA> <NA> NA 5 NA
2 HA-09 16 <33% no/occasional NA NA 1
3 HA-10 20 no <NA> NA 2 NA
4 HA-10 20 yes <NA> 0 NA NA
这仍然可以实现,但摘要的自定义函数(我们称之为
f
)会变得更加复杂:
f <- function(x) {
x <- x[!is.na(x$value),]
if (nrow(x) > 0) {
y <- unique(x[colnames(x) != 'row.ID'])
y$row.ID <- 1:nrow(y)
return(y)
} else {
return(data.frame())
}
}
请注意,此函数引用了一个名为“row.ID”的列,我们将在应用函数之前创建该列:
library(tidyverse) # gives access to dplyr and tidyr packages
b2 <- gather(b, variable, value, -ID, -Age) %>% # gather the many columns into a simplified key/value pair of columns (one called 'variable', the other, 'value') for each ID
group_by(ID, variable) %>% # perform subsequent operations per ID and variable
mutate(row.ID = 1:n()) %>% # add a row identifier
do(f(.)) %>% # apply our custom function
spread(variable, value, convert = T) %>% # un-gather the variable/value columns
ungroup # remove grouping metadata
ID Age row.ID Bili.AHHS2cat Lille_3 Lille_dico Mallory Steatosis
* <fctr> <int> <int> <int> <int> <int> <chr> <chr>
1 HA-09 16 1 1 5 NA no/occasional <33%
2 HA-10 20 1 NA 2 0 <NA> no
3 HA-10 20 2 NA NA NA <NA> yes
paste(x,collapse = '-')
而不是first(x)
来保留多个值。 - jdobres