R:R在apply中创建多个值
我有一个函数,可以从API中获取多个数字,并将其输入到数据帧中。我想使用一个apply函数将我的数据帧挂接到这个函数上,并为每一行准确地调用它一次。这里是我的可复制示例:R:R在apply中创建多个值,r,dataframe,apply,R,Dataframe,Apply,我有一个函数,可以从API中获取多个数字,并将其输入到数据帧中。我想使用一个apply函数将我的数据帧挂接到这个函数上,并为每一行准确地调用它一次。这里是我的可复制示例: # create data frame df = data.frame(Long=c(0.0, 0.0 , 0.0), Lat=c(0.0, 0.0, 0.0), c=c("test1", "test2", "test3")) # random number betweeen 1 and 10 rand1 = functi
# create data frame
df = data.frame(Long=c(0.0, 0.0 , 0.0), Lat=c(0.0, 0.0, 0.0), c=c("test1", "test2", "test3"))
# random number betweeen 1 and 10
rand1 = function(){
sample(1:10, 1)
}
# random number betweeen 1 and 10
rand2 = function(){
sample(100:500, 1)
}
# calls the "API" --- simplified with two random numbers coming from two functions
callAPI = function(entry){
entry[1] = rand1()
entry[2] = rand2()
}
# run my function
df[,1] <- apply(df, 1, callAPI)
df
#创建数据帧
df=data.frame(Long=c(0.0,0.0,0.0),Lat=c(0.0,0.0,0.0),c=c(“test1”,“test2”,“test3”))
#介于1和10之间的随机数
rand1=函数(){
样本(1:10,1)
}
#介于1和10之间的随机数
rand2=函数(){
样本(100:500,1)
}
#调用“API”——简化为来自两个函数的两个随机数
callAPI=函数(条目){
条目[1]=rand1()
条目[2]=rand2()
}
#运行我的函数
df[,1]您的函数只返回最后一个值。您需要同时返回这两个值
callAPI <- function(entry){
output <- c(rand1(), rand2())
return(output)
}
函数只返回最后一个值。您需要同时返回这两个值
callAPI <- function(entry){
output <- c(rand1(), rand2())
return(output)
}