gpt4 book ai didi

r - R中的函数参数定义问题

转载 作者:行者123 更新时间:2023-12-04 11:47:57 25 4
gpt4 key购买 nike

这是我的问题,当我想开发一个广泛使用的功能时。

dataframe1 <- data.frame(V1 = 1:10, V2 = 11:20, V3 = 21:30, V4 = 31:40)
myfun <- function (dataframe, A, B, yvar) {
dataframe1$A <- as.factor(dataframe$A)
dataframe1$B <- as.factor (dataframe$B)
dataframe1 <- data.frame(A = dataframe1$A,
B = dataframe1$B, yvar = dataframe1$yvar)
print(dataframe1)
}

myfun (dataframe = dataframe1, A = "V1", B= "V2", yvar = "V3")
Error in `$<-.data.frame`(`*tmp*`, "A", value = integer(0)) :
replacement has 0 rows, data has 10

myfun (dataframe = dataframe1, A = dataframe1$V1,
B= dataframe1$V2, yvar = dataframe1$V3)
Error in `$<-.data.frame`(`*tmp*`, "A", value = integer(0)) :
replacement has 0 rows, data has 10

我想使用第一种类型的定义来定义,其中变量名参数在“括号”而不是“datafile$variablename”中

最佳答案

您只需要不使用 $ 作为列选择器。相反,使用 [:

dataframe[,A]

dataframe[,B]

等等。在你的情况下:

dataframe1 <- data.frame(V1 = 1:10, V2 = 11:20, V3 = 21:30, V4 = 31:40)
myfun <- function (dataframe, A, B, yvar) {
dataframe1[,A] <- as.factor(dataframe[,A])
dataframe1[,B] <- as.factor (dataframe[,B])
dataframe1 <- data.frame(A = dataframe1[,A],
B = dataframe1[,B], yvar = dataframe1[,yvar])
print(dataframe1)
}

myfun (dataframe = dataframe1, A = "V1", B= "V2", yvar = "V3")

A B yvar
1 1 11 21
2 2 12 22
3 3 13 23
4 4 14 24
5 5 15 25
6 6 16 26
7 7 17 27
8 8 18 28
9 9 19 29
10 10 20 30

关于r - R中的函数参数定义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8195279/

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