与python中一样,r中的For循环

与python中一样,r中的For循环,python,r,for-loop,Python,R,For Loop,在R中是否可能有一个类似于Python的for循环,在for循环中应用两个元素(x,y) 对于键,dict.items()中的值: 打印(键、值) 你的意思是这样的 df <- data.frame( x = c(1,2,3,4) , y = c("a", "b", "c", "d") ) for (i in 1:nrow(df)){ print(df$y[i]) } dfdict_py={'a

在R中是否可能有一个类似于Python的for循环,在for循环中应用两个元素(x,y)

对于键,dict.items()中的值:
打印(键、值)

你的意思是这样的

df <- data.frame(
  x = c(1,2,3,4)
  , y = c("a", "b", "c", "d")
)

for (i in 1:nrow(df)){
  print(df$y[i])
}
df
dict_py={'a':1,'b':2,'c':3,'d':4}
##蟒蛇
#成对打印字典元素:
对于dict_py.items()中的x,y:
打印(x,y)
##a 1
##b 2
##C3
##d 4
#python允许对每个元素应用不同的函数:
t1=[]
t2=[]
对于dict_py.items()中的x,y:
t1.附加(x+“zz”)
t2.追加(y**2)
打印(t1、t2)
##[1,4,9,16]
#R中的数据帧示例

为什么是嵌套循环?我不明白你在问什么。在R@juanpa.arrivillaga中,您到底想实现什么?@juanpa.arrivillaga,很抱歉没有恰当地解释我的问题,我的意思是,我们可以同时在for循环中放置两个项,以打印数据帧的元素,例如在R编码中:for(i,x in df[,]){print(i)print(n)}。而不是:for(i in length(df)){for x in nrow(df)){print(df[x,i]}}。我相信您正在寻找类似
mapply()
,类似
mapply(函数(x,y)粘贴(x,y),1:4,2:5)
@Wimpel,这是一条很有帮助的评论,我会根据您的评论编写我的解决方案,并做一些修改。但总体而言,这一python功能似乎还没有在R中实现。@Roeof Waaijman,您的代码只打印y列。我的意思是在数据帧之外,将每一对紧挨着打印。@Roeof Waaijman,谢谢您的帮助答案,但我的问题是关于(x,y),“for loop”中的两个元素,意思是:for(x,y在df中),而不是一个元素(for(x在df中))。这对我来说不是一个问题,但如果在r中有类似的功能,可能会使一些代码行更短更简单。请将代码作为代码发布(即在代码块中使用文本),不是图像!图像是完全无法搜索的,对视力受损的人来说…@Ben Bolker,好的,你的权利,我把它贴在一个代码块中。
df <- list(
  x = c(1,2,3,4)
  , y = c("a", "b", "c", "d")
)

for (i in 1:length(df$x)){
  print(paste(df[['x']][i], df[['y']][i]))
}
dict_py = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}

## python
# print dictionary elements as paired: 

for x,y in dict_py.items():
    print(x,y)
## a 1
## b 2
## c 3
## d 4

# python allows applying different function to each elements:

t1 = []
t2 = []
for x,y in dict_py.items():
    t1.append(x + "zz")
    t2.append(y**2)


print(t1, t2)

## ['azz', 'bzz', 'czz', 'dzz'] [1, 4, 9, 16]

# dataframe example in R
df <- data.frame(
  first = c("a", "b", "c", "d"),
  second = c(1,2,3,4)
)

#mapply function to print paired values(paste or print)
#with paste

func1 <-mapply(function(x,y) paste(x,y), df['first'], df['second'])

colnames(func1) <-NULL

print(func1)
##      [,1] 
## [1,] "a 1"
## [2,] "b 2"
## [3,] "c 3"
## [4,] "d 4"

#with print
func2 <- mapply(function(x,y) print(c(x,y)), df[,'first'], df[,'second'])

## [1] "a" "1"
## [1] "b" "2"
## [1] "c" "3"
## [1] "d" "4"

#other example

mapply(function(x,y) print(c(x,y)), df[,'first'], df[,'second'])[0]
## [1] "a" "1"
## [1] "b" "2"
## [1] "c" "3"
## [1] "d" "4"
## character(0)