如何使用R编程比较表中的元素

时间:2018-02-19 02:41:41

标签: r

我希望将第2列的每个元素与增加值1到10进行比较。如果匹配,我想计算并将它们打印在一个新文件中,其中包含制表符。 例如:

X   Y
1   1
2   1
3   1
4   2
5   2
6   2
7   4
8   4
9   4
10  4

我想检查Y列是否与1匹配(在这种情况下,它匹配3次) 所以我希望在文件output.txt

中按如下方式打印输出
output.txt
[result]
1    2   3

接下来想要查找值为2的Y列(在这种情况下我有3个匹配)所以想要将计数追加到output.txt

output.txt
[result]
1    2   3
4    5   6

接下来想要查找值为4的Y列(在这种情况下我有4个匹配)所以想要将计数追加到output.txt

output.txt
[result]
1    2   3
4    5   6
7    8   9   10

我是初学者,非常感谢你的帮助。

谢谢和问候, Bikash

2 个答案:

答案 0 :(得分:0)

我不确定我是否提出了您的问题,但您希望getBoundingClientRect()像对抗一样行事?即它中的最后一个数字值应该表示文件的最后一行?您可以使用Marker来执行此操作:

output.txt

这将打印在writeLines

  

1 2 3 4

(在您的示例中,## The example data (with nothing in column X) Y <- c(1, 1, 2, 1, 3, 1, 4, 2, 5, 2, 6, 2, 7, 4, 8, 4, 9, 4, 10, 4) X <- NA ## Making a data frame data_frame <- data.frame(cbind(X, Y)) ## Selecting the unique elements in Y unique_Y <- unique(data_frame$Y) ## Create the output file connection_output <- file("output.txt", "w") ## Initialise the position where to write the text position <- 0 ## Looping through each unique element for(row in unique_Y) { ## Get the occurences of the variable row matches <- which(data_frame$Y == row) ## Append the text writeLines(as.character(position + 1:length(matches)), con = connection_output, sep = " ") ## Update the counter position <- position + length(matches) } ## Close the connection close(connection_output) output.txt1的数量的序列 - 4)。然后将附加为:

  

1 2 3 4 5 6 7 8

(在您的示例中,1Y5的数量的序列 - 4)。然后:

  

1 2 3 4 5 6 7 8 9

2Y9的数量的序列 - 在您的示例中为1)。等

答案 1 :(得分:0)

您可以splitXY列,然后使用cat发送到文件:

cat(sapply(split(dat$X, dat$Y), paste, collapse="\t"), sep="\n")
#1       2       3
#4       5       6
#7       8       9       10