R:将文本值从数据框的一个单元格复制到另一个数据框的另一个单元格

R: Copying text values from a cell of a dataframe to another cell of another dataframe

对于更改问题的内容,我深表歉意,但我刚刚意识到问题与循环无关(我收到了不好的结果,我最初认为循环有问题。对此我深表歉意).所以我现在写的是实际问题:

我想将一个数据框单元格的文本值传输到另一个数据框单元格的另一个文本值中。

例如:

dataframe1:

id text
1  athens
2  greece

dataframe2:
id  wordmatch
1   NA
2   NA

我正在使用以下命令:

dataframe2$wordmatch[1] <- dataframe1$text[1]

但我没有在 dataframe2$wordmatch[1] 中使用值 "athens",而是使用值“1”。

新答案:

这种意外行为是由于 df1 的文本列可能是 factor 而不是 character 造成的,要验证,请尝试 class(df1$text)。您可以通过以下任一方式解决您的问题

df1$text <- as.character(df1$text)

dataframe2$wordmatch[1] <- as.character(dataframe1$text[1])

希望对您有所帮助。


关于循环的旧答案:

是的,那应该没问题。一个有效的例子是:

df = data.frame(nofdelet=c(2,3,4,2))

my_func <- function(i,j)
{
  print(paste0('i: ', i, ', j: ', j))
}

for(i in 1:nrow(df))
{
  for (j in 1:df$nofdelet[i])
  {
    my_func(i,j)
  }
}

输出:

[1] "i: 1, j: 1"
[1] "i: 1, j: 2"
[1] "i: 2, j: 1"
[1] "i: 2, j: 2"
[1] "i: 2, j: 3"
[1] "i: 3, j: 1"
[1] "i: 3, j: 2"
[1] "i: 3, j: 3"
[1] "i: 3, j: 4"
[1] "i: 4, j: 1"
[1] "i: 4, j: 2"

请注意,您不必初始化循环变量 ij。希望这会有所帮助。

你的代码适用于我的测试用例。

repetition <- c(1, 2, 3, 4, 5)
df <- data.frame(repetition)

for(i in 1:length(repetition)){
  for(d in 1:df$repetition[i]){
    print(i)
  }
}

在循环中使用它们之前不需要指定 id

我的示例的输出符合预期:

[1] 1
[1] 2
[1] 2
[1] 3
[1] 3
[1] 3
[1] 4
[1] 4
[1] 4
[1] 4
[1] 5
[1] 5
[1] 5
[1] 5
[1] 5

E:我刚刚注意到您的代码使用了 for( i in 1:nrow(Sample)){。不应该是 sample 吗?也许您应该检查您的代码是否存在区分大小写的错误。

我找到了答案。需要使用函数paste()

dataframe2$wordmatch[1] <- paste(dataframe1$text[1])