创建一个新列,该列在R中的新列中具有唯一值的总数
我想创建一个新列,其中包含另一列唯一实例的总数。
x <- c("1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "6", "6", "6")
y <- c("Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y")
df <- data.frame(x, y)
我想要的是以下内容:
# x y z
#
# 1 Y 4
# 1 Y 4
# 1 Y 4
# 1 Y 4
# 2 N 3
# 2 N 3
# 2 Y 3
# 3 Y 3
# 3 Y 3
# 3 Y 3
# 4 Y 2
# 4 Y 2
# 5 Y 1
# 6 N 3
# 6 Y 3
# 6 Y 3
我完成了以下脚本,但它被糊涂了。
library(plyr)
library(dplyr)
library(purrr)
library(tidyverse)
library(ggtext)
library(stringr)
x <- c("1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "6", "6", "6")
y <- c("Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y")
df <- data.frame(x, y)
unique_count <- as.data.frame(table(df$x))
colnames(unique_count)[1] <- "x"
colnames(unique_count)[2] <- "z"
df <- purrr::reduce(list(df,unique_count), dplyr::left_join, by = 'x')
I want to create a new column, which contains the totals count of a unique instance of another column.
x <- c("1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "6", "6", "6")
y <- c("Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y")
df <- data.frame(x, y)
What I want is the following:
# x y z
#
# 1 Y 4
# 1 Y 4
# 1 Y 4
# 1 Y 4
# 2 N 3
# 2 N 3
# 2 Y 3
# 3 Y 3
# 3 Y 3
# 3 Y 3
# 4 Y 2
# 4 Y 2
# 5 Y 1
# 6 N 3
# 6 Y 3
# 6 Y 3
I have done the following script but it is convuluted.
library(plyr)
library(dplyr)
library(purrr)
library(tidyverse)
library(ggtext)
library(stringr)
x <- c("1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "6", "6", "6")
y <- c("Y", "Y", "Y", "Y", "N", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y", "Y")
df <- data.frame(x, y)
unique_count <- as.data.frame(table(df$x))
colnames(unique_count)[1] <- "x"
colnames(unique_count)[2] <- "z"
df <- purrr::reduce(list(df,unique_count), dplyr::left_join, by = 'x')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个可能的解决方案:
A possible solution:
这与@pauls的答案完全相同,但仅与其他单词和一行相同!
This is exactly the same as @Pauls answer, but just with other words and one line more!
这可以通过以下文章来回答: dplyr:将计数放入新的可变<< /a>
您需要按变量x和y对数据进行分组,并计算这些组合的发生。使用Dplyr A解决方案将是:
输出:
This can be answered by the following post: dplyr: put count occurrences into new variable
You need to group your data by variable x and y and count the occurences of these combinations. With dplyr a solution would then be:
Output: