简体   繁体   English

需要协助以了解R的循环错误:“”中意外的'}'

[英]Need assistance with understanding R for loop error: unexpected '}' in “ }”

Just to give some background first: 只是先给一些背景知识:

I currently have 2 data frames (giraffe, leaf) and both of them share the column 'key', where the elements in the leaf data frame are a subset of giraffe. 我目前有2个数据框(长颈鹿,叶子),并且它们都共享“键”列,其中叶子数据框中的元素是长颈鹿的一个子集。 What I needed to do is compare the two data frames and when there are matching elements in both data frames in the 'key' column, the string 'leaf' will be input into another column (project) in the giraffe data frame inside the same row as the matching 'key' element. 我需要做的是比较两个数据帧,并且当“键”列中的两个数据帧中都有匹配的元素时,字符串“叶”将被输入到同一长颈鹿数据帧中的另一列(项目)中行作为匹配的“键”元素。 I've taken the following approach however it seems I have made a small error somewhere and after searching online, I still don't know what it is: 我采用了以下方法,但是似乎我在某个地方犯了一个小错误,并且在网上搜索后,我仍然不知道它是什么:

Truth_vector <- is.element((giraffe[,1]),(leaf[,1])) #returns a vector with 3000 elements, most are FALSE except for where the element inside 'key' is present in both data frames Truth_vector <- is.element((giraffe[,1]),(leaf[,1])) #返回一个包含3000个元素的向量,大多数都是FALSE,除了两个数据帧中都存在'key'内部的元素

i=1
for (i in 1:length(giraffe[,1])) {
  if Truth_vector[i] == TRUE {
   giraffe[i,5] <- 'leaf'
  }
  i = i+1
}

Error: unexpected '}' in "}"

Edit: 编辑:

I tried implementing the solution as a function however nothing ends up happening, no error messages get returned either. 我尝试将解决方案实现为函数,但是最终没有发生任何事情,也没有返回错误消息。 What I've done is: 我所做的是:

Project_assign <- function(prjct) {
Truth_vector <- is.element((giraffe[,1]),(prjct[,1]))
giraffe[which(Truth_vector),5] <- 'prjct'
}
Project_assign(leaf)

Edit: This was because everything was getting assigned in the function sub environment, not the global environment. 编辑:这是因为一切都在功能子环境中分配了,而不是在全局环境中分配了。 Using assign('giraffe',giraffe,envir=.GlobalEnv) solves this however you should try and avoid the assign function and Instead I used a for loop going over a list of all the dataframes 使用assign('giraffe',giraffe,envir = .GlobalEnv)可以解决此问题,但是您应该尝试避免使用assign函数,而是使用for循环遍历所有数据帧的列表

You have a couple issues. 你有几个问题。 First, the if criteria needs to be in parentheses, and secondly you don't need to increment i yourself. 首先,if条件必须放在括号中,其次您不需要自己增加i This should suffice: 这样就足够了:

for (i in 1:length(giraffe[,1])) {
  if (Truth_vector[i] == TRUE) {
   giraffe[i,5] <- 'leaf'
  }
}

Of course, this would do it too: 当然,这也可以做到:

giraffe[which(Truth_vector),5] <- 'leaf'

(assuming Truth_vector is not longer than the number of rows in giraffe) (假设Truth_vector不超过长颈鹿中的行数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM