将数据框的两个列向量转换为单个数字列

Converting two column vectors of a data frame into a single numeric column

考虑我的种子研究的以下玩具数据框:

site <- c(LETTERS[1:12])          
site1 <- rep(site,each=80)

fate <- c('germinated', 'viable', 'dead')
fate1 <- rep(fate,each=320)

number <- c(41:1000)

df <- data.frame(site1,fate1,number)

> str(df)
'data.frame':   960 obs. of  3 variables:
 $ site1 : Factor w/ 12 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ fate1 : Factor w/ 3 levels "dead","germinated",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ number: int  41 42 43 44 45 46 47 48 49 50 ...

我希望 R 遍历 "dead" 的所有观察结果并将 "0" 分配给每个观察结果他们。同样,我想将 "1" 分配给所有 "viable" 观察和 "2" 所有 "germinated" 观察。

我的最终数据框将是单列,有点像这样:

> year16
  [1] 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0
 [38] 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1

非常欢迎所有建议

使用 dplyr 库中的 case_when

df$year16 <-
case_when(
    levels(df$fate1)[df$fate1] == "dead" ~ 0,
    levels(df$fate1)[df$fate1] == "viable" ~ 1,
    levels(df$fate1)[df$fate1] == "germinated" ~ 2,
    TRUE ~ -1
)

注意:@David 和@kath 给出的解决方案比这更优雅,但即使我们有非数字替换,我上面给出的仍然有效。

基础 R 解决方案:

assignnum <- function(x) {

  if (x == 'viable') {
    z <- 1
} else if (x == 'dead') {
  z <- 0
} else if (x == 'germinated') {
  z <- 2  
}
  return(z)
}

df['result'] <- sapply(df$fate1, assignnum)

正如zx8754所说,你可以看看一个因素的属性。

year16 <- as.numeric(factor(df$fate1, levels = c("dead", "viable", "germinated")))-1

这里我先把df$fate1的层级重新排序,所以dead赋值为1,viable赋值为2,generated赋值为3。你要从0开始序列,所以转完之后还要减1数值变量中的因子。