简体   繁体   English

在 R 中应用和应用行为

[英]Sapply and apply behaviour in R

Consider the following df :考虑以下df

structure(list(GID7173723 = c("A", "T", "G", "A", "G"), GID4878677 = c("G", 
"C", "G", "A", "G"), GID88208 = c("A", "T", "G", "A", "G"), GID346403 = c("A", 
"T", "G", "A", "G"), GID268825 = c("G", "C", "G", "A", "G")), row.names = c(NA, 
5L), class = "data.frame")

Looks like this:看起来像这样:

  GID7173723 GID4878677 GID88208 GID346403 GID268825
1          A          G        A         A         G
2          T          C        T         T         C
3          G          G        G         G         G
4          A          A        A         A         A
5          G          G        G         G         G

And the following function:以及以下 function:

f = function(x){
  ifelse(x=='A',x<-1,x) 
}

Using apply everything runs well as I expect:使用apply一切运行良好,如我所料:

    apply(df, 1,f)

          1   2   3   4   5  
GID7173723 "1" "T" "G" "1" "G"
GID4878677 "1" "C" "G" "1" "G"
GID88208   "1" "T" "G" "1" "G"
GID346403  "1" "T" "G" "1" "G"
GID268825  "1" "C" "G" "1" "G"

But if I use sapply or lapply all the values are converted to 1:但如果我使用sapplylapply所有值都转换为 1:

> sapply(dfn,f)
     GID7173723 GID4878677 GID88208 GID346403 GID268825
[1,]          1          1        1         1         1
[2,]          1          1        1         1         1
[3,]          1          1        1         1         1
[4,]          1          1        1         1         1
[5,]          1          1        1         1         1

I read from the documentation that lapply and sapply applies FUN to every element.我从文档中lapplysapplyFUN应用于每个元素。 Why is everything being converted to 1?为什么一切都被转换为1? Is there anything to do with R coercing integers to strings? R 将整数强制转换为字符串有什么关系? Please help.请帮忙。

One other aspect which I don't understand is why with this new function I have only a vector with 5 elements instead of a dataframe filled with 'G':我不明白的另一个方面是为什么使用这个新的 function 我只有一个包含 5 个元素的vector ,而不是一个充满“G”的dataframe

    f2 = function(x) x<-'G'

> sapply(dfn,f2)
GID7173723 GID4878677   GID88208  GID346403  GID268825 
       "G"        "G"        "G"        "G"        "G" 

> apply(dfn, 1,f2)
  1   2   3   4   5 
"G" "G" "G" "G" "G" 
  • apply takes df or matrix as input, and outputs=>vector, list, array apply 将 df 或矩阵作为输入,输出=>vector, list, array
  • lapply takes df, list or vector as input, and outputs=> list lapply 将 df、list 或 vector 作为输入,输出=> list
  • sapply takes df, list or vector as input, and outputs=> vector or matrix sapply 将 df、list 或 vector 作为输入,outputs=> 向量或矩阵

1st question.第一个问题。 If you use如果你使用

apply(df, 2,f)

you will also get a table full of 1s.你还会得到一张满是 1 的桌子。 R is not converting strings to integers. R 未将字符串转换为整数。

2nd question.第二个问题。 Try this as 1 is used for rows, and 2 is for columns.试试这个,因为 1 用于行,2 用于列。

apply(df, 2,f2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM