简体   繁体   English

将自定义函数应用于R中的列

[英]apply custom function to columns in R

Here is my code, I expect it to insert zero into second place of every column, but it does not work. 这是我的代码,我希望它可以将零插入每列的第二位,但是它不起作用。

insert_zero <- function(smpl_vec){
  return(smpl_vec[2]<-0)
}

my_df = data.frame('col_1'= c(1,2,3), 'col_2'= c(2,3,4))
apply(my_df, 2, insert_zero)

How can I fix it? 我该如何解决?

PS This is just simplified example. PS这只是简化的示例。 Actual function is more complicated. 实际功能更加复杂。

You can replace the entire second row with zeros: 您可以将整个第二行替换为零:

my_df[2, ] <- 0 

Be aware that my_df is a data.frame with rows and columns 请注意, my_df是具有行和列的data.frame

You're only returning the 2nd value in each column with your current function. 您只需使用当前函数在每一列中返回第二个值。 This change will make the second value 0 but still return each column in their entirety: 此更改将使第二个值变为0,但仍完整返回每一列:

insert_zero <- function(smpl_vec){
  smpl_vec[2] <- 0
  return(smpl_vec)
}

my_df = data.frame('col_1'= c(1,2,3), 'col_2'= c(2,3,4))
apply(my_df, 2, insert_zero)

return(smpl_vec[2]<-0) doesn't return the modified vector return(smpl_vec[2]<-0)不返回修改后的向量

insert_zero <- function(smpl_vec){
  smpl_vec[2]<-0
  return(smpl_vec)
}

Thank you for asking this question. 感谢您提出这个问题。 While looking for a solution, I did learn something new. 在寻找解决方案时,我确实学到了一些新知识。 While assigning a new value to cell 在为单元格分配新值时

 1)  use '<' twice. Below is the statement
 2)  mention the dataframe row and column numbers as mentioned. Below is the modified code

    insert_zero <- function(smpl_vec){
               my_df[2,smpl_vec] <<- 0

            }

          my_df = data.frame('col_1'= c(1,2,3), 'col_2'= c(2,3,4))
          sapply(1:ncol(my_df), function(smpl_vec) insert_zero(smpl_vec))

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

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