假设我有几个数据帧,我想遍历每个数据帧的行并做一些事情,比如使用httr
包发送 SMS 消息。我可以创建几个循环,但我怀疑答案是“不要使用循环!”。
df1 <- data.frame(A=1:10, B=2:11, C=3:12) # imagine these columns hold words and phone numbers
df2 <- data.frame(A=4:13, B=5:14, C=6:15)
# loop for df1
for (n in 1:nrow(df1)) { # imagine that each row is a person
# get details for each person (row)
sms1 <- df1$A[n]
sms2 <- df1$B[n]
sms3 <- df1$C[n]
# create personalized message to send
sms <- paste(sms1, sms2, sms3, sep=" ")
# here I would use the POST() function of httr to send a personalized SMS to each person, but that is not important
}
# loop for df2
for (n in 1:nrow(df1)) {
sms1 <- df2$A[n]
sms2 <- df2$B[n]
sms3 <- df2$C[n]
sms <- paste(sms1, sms2, sms3, sep=" ")
# here I would use the POST() function of httr to send a personalized SMS, but that is not important
}
但我真正想做的是创建一个外部循环来遍历每个数据帧。就像是:
dfs <- c("df1", "df2")
# loop over dfs
for (d in dfs) {
for (n in 1:nrow(d)) {
sms1 <- d$A[n]
sms2 <- d$B[n]
sms3 <- d$C[n]
sms <- paste(sms1, sms2, sms3, sep=" ")
# here I would use the POST() function of httr to send a personalized SMS, but that is not important
}
}
但我知道这行不通。我d
的 insms1 <- d$A[n]
不会被读作sms1 <- df1$A[n]
or sms1 <- df2$A[n]
。
有没有办法做这个循环?更好的是,正确的应用方法是什么?
更新:
这是我需要对两个数据帧中的每一行执行的 POST 步骤的示例,以向每个人(行)发送个性化消息:
# let's say that sms3 in my example is a phone number
# let's also say that I define the following objects once outside of the loop:
# url, username, password, account, source, network
# when I paste together the following objects, I get string that is formatted for my API gateway.
send <- paste0(url, username, password, account, source, sms3,
sms, network)
POST(send)
正如我原始帖子的评论中提到的那样,这将进入循环:
# remove these paste steps from the loops as recommended in the answers
df1$sms <- paste(df2$A, df2$B)
df2$sms <- paste(df2$A, df2$B)
dfs <- c("df1", "df2")
# loop over dfs
for (d in dfs) {
for (n in 1:nrow(d)) {
sms3 <- d$C[n] # to get phone number
send <- paste0(url, username, password, account, source, sms3, sms, network)
POST(send)
}
}