gpt4 book ai didi

r - 如何在函数调用中使用 data.table?

转载 作者:行者123 更新时间:2023-12-04 10:43:53 29 4
gpt4 key购买 nike

1

我想用data.table在自定义函数中,我收到错误:

> library(data.table)
> DT = data.table(a = c(6,3,1,9,NA), b = 4:8)
> DT
a b
1: 6 4
2: 3 5
3: 1 6
4: 9 7
5: NA 8
> fillna = function(df,var){
+ col = df[[var]]
+ set(df, i = which(is.na(col)), j = var, value = mean(col, na.rm=T))
+ }
>
> fillna(DT,a)
Error in (function(x, i, exact) if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, :
object 'a' not found
>

如何解决?

2

我也尝试使用 get()从这篇文章:

Making function with data.table in R

但它仍然失败:
> fillna = function(df,var){
+ df[is.na(get(var)),var:=mean(df[[var]],na.rm = T)]
+ df
+ }
>
> fillna(DT,a)
Error in .checkTypos(e, names_x) :
Object 'a' not found. Perhaps you intended a, b

最佳答案

一个简单的解决方法是将列名作为字符串传递

fillna = function(df,var){
col = df[[var]]
set(df, i = which(is.na(col)), j = var, value = mean(col, na.rm=T))
return(df)
}

fillna(DT,"a")

# a b
#1: 6.00 4
#2: 3.00 5
#3: 1.00 6
#4: 9.00 7
#5: 4.75 8

关于r - 如何在函数调用中使用 data.table?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807039/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com