简体   繁体   English

在 R 中将两列数据框合并在一起

[英]Binning two columns of data frame together in R

I would like to bin two columns of a dataset simultaneously to create one common binned column.我想同时合并数据集的两列以创建一个通用的合并列。 The simple code is as follows简单代码如下

x <- sample(100)
y <- sample(100)

data <- data.frame(x, y)

xbin <- seq(from = 0, to = 100, by = 10)
ybin <- seq(from = 0, to = 100, by = 10)

Any help is appreciated!任何帮助表示赞赏!

After asking in the comments I am still not quite shure, what the desired answer would look like but I hope, that one of the two answers in the below code will work for you:在评论中询问后,我仍然不太确定所需的答案是什么样的,但我希望以下代码中的两个答案之一对您有用:

x <- sample(100)
y <- sample(100)
data <- data.frame(x, y)
xbin <- seq(from = 0, to = 100, by = 10)
ybin <- seq(from = 0, to = 100, by = 10)

data$xbin <- cut(data$x, breaks = xbin, ordered = TRUE)
data$ybin <- cut(data$y, breaks = ybin, ordered = TRUE)
data$commonbin1 <- paste0(data$xbin, data$ybin)
data$commonbin2 <- paste0("(",as.numeric(data$xbin),";", as.numeric(data$ybin),")")

head(data, 20)

This will construct a common binning variable commonbin1 that includes the bin-limits in the names of the bins and commonbin2 which will be easier to compare to the plot mentioned in the comment.这将构造一个公共分箱变量commonbin1 ,其中包括 bin 名称中的 bin 限制和commonbin2 ,这将更容易与评论中提到的 plot 进行比较。

Not sure if this is what you are looking for不确定这是否是您要找的

library(tidyverse)

x <- sample(100)
y <- sample(100)

data <- data.frame(x, y)

xbin <- seq(from = 0, to = 100, by = 10)
ybin <- seq(from = 0, to = 100, by = 10)


data <- data%>%
  dplyr::mutate(
    x_binned = cut(x, breaks = seq(0,100,10)),
    y_binned = cut(y, breaks = seq(0,100,10))
  )

data %>% 
  ggplot() +
  geom_bin_2d(
    aes(x = x_binned, y = y_binned), binwidth = c(10,10), colour = "red") +
  theme_minimal()

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

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