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
}
}
しかし、私はこれがうまくいかないことを知っています。My d
inはorsms1 <- d$A[n]
とは読みません。sms1 <- df1$A[n]
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)
}
}