我正在嘗試在 R 中轉換 Python 中的 double for 回圈。當我在 paste 函式中使用它時它可以正常作業。我試圖弄清楚為什么沒有它就無法訪問這些。
在 Python 中
l1 = ['appetizer','main course']
l2 = ['italian','mexican','french']
for i in l1:
for j in l2:
print(i,j)
在 R
l1 = list('appetizer','main course')
l2 = list('italian','mexican','french')
這會引發錯誤
for (i in l1) {
for (j in l2) {
print(i,j)
}
}
錯誤
Error in print.default(i, j) : invalid 'digits' argument
In addition: Warning message:
In print.default(i, j) : NAs introduced by coercion
> for (i in l1) {
這不會引發錯誤
for (i in l1) {
for (j in l2) {
print(paste(i,j,sep=","))
}
}
輸出
[1] "appetizer,italian"
[1] "appetizer,mexican"
[1] "appetizer,french"
[1] "main course,italian"
[1] "main course,mexican"
[1] "main course,french"
uj5u.com熱心網友回復:
索引之間存在差異。Python 將向量(陣列)作為索引傳遞,而 R 傳遞值。請注意,索引以 開頭1
,即1, 2, ..., n。您還需要連接c
要列印的物件,將它們作為單個引數傳遞。因此,您可以執行以下操作:
l1 <- list('appetizer', 'main course')
l2 <- list('italian', 'mexican', 'french')
for (i in seq_along(l1)) {
for (j in seq_along(l2)) {
print(c(l1[[i]], l2[[j]]))
}
}
# [1] "appetizer" "italian"
# [1] "appetizer" "mexican"
# [1] "appetizer" "french"
# [1] "main course" "italian"
# [1] "main course" "mexican"
# [1] "main course" "french"
uj5u.com熱心網友回復:
請參閱下面的print
方法說明。
print(x, digits = NULL, quote = TRUE,
na.print = NULL, print.gap = NULL, right = FALSE,
max = NULL, useSource = TRUE, …)
x the object to be printed.
digits a non-null value for digits specifies the minimum number of
significant digits to be printed in values. The default, NULL, uses
getOption("digits"). (For the interpretation for complex numbers see
signif.) Non-integer values will be rounded down, and only values
greater than or equal to 1 and no greater than 22 are accepted.
...
顯然,第二個變數不被接受為有效引數。
雖然這有點奇怪,但更重要的一點是 print(a,b) 不是列印多個值的語法正確方法。
所以你可以繼續使用paste()
功能
或索引之類的 print(c(l1[[i]], l2[[j]]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/402164.html
下一篇:正則運算式匹配/中斷