R:将标题从for循环添加到散点图

时间:2018-11-16 17:03:02

标签: r dataframe for-loop

我对R很陌生,似乎无法解决以下问题:

我有一个带有不同变量(=列)的数据框,这些变量要么是预测变量,要么是目标变量。我想查看每个预测变量和每个目标之间的散点图(出于计算原因,我不想查看所有pariwise散点图)。我编写了一个嵌套的for循环来创建散点图,效果很好。但是,我无法在散点图上添加标题以指示两个相关功能。

我写了一个简单的例子:

#create dataframe
f1 = rnorm(100)
f2 = rnorm(100)
f3 = rnorm(100)
t1 = rnorm(100)
t2 = rnorm(100)
mydata = data.frame(f1, f2, f3, t1, t2)

#defining targets & features by vectors
targets <- c("t1", "t2")
features <- c("f1", "f2", "f3")

#wrong solution
for (i in mydata[,features]){
 for (j in mydata[,targets]){
  plot= plot(i, j, main = paste(names(mydata)[i], "vs", names(mydata)[j]))
}}

这显然不起作用。

有人知道我在做什么错吗? 理想情况下,我想将两个变量的名称添加到每个散点图和相应的轴。

2 个答案:

答案 0 :(得分:1)

如果可以的话,请首先在代码块中包含最小的可重现示例,这使人们可以轻松复制和粘贴您的代码。

根据您的示例,names(mydata[i])不起作用的原因是i包含列中的所有值,而不是对该列的引用。另外,您通常希望更像names(mydata)[i]之类的东西从名称向量中选择一个值。

要将名称添加到散点图中,请尝试以下操作:

# Sample data
f1 <- rnorm(100)
f2 <- rnorm(100)
f3 <- rnorm(100)
t1 <- rnorm(100)
t2 <- rnorm(100)
df <- data.frame(f1, f2, f3, t1, t2)

# Features, Targets to compare
targets <- c('t1', 't2')
features <- c('f1', 'f2', 'f3')

# The nested for loop.
for (i in features) {
  # i = 'f1', 'f2', 'f3', 'fn'
  for (j in targets) {
    # j = 't1', 't2', 'tn'
    p <- plot(
      df[[i]], # Reference to the dataframe column titled 'fn'
      df[[j]], # Reference to the dataframe column titled 'tn'
      main = paste(i, 'x', j), # Title using the strings
      xlab = i, # x-axis title
      ylab = j  # y-axis title
    )
  }
}

答案 1 :(得分:0)

您只需选择两个功能并将其传递到paste0()中,如下所示:

feature1<- rnorm(100)
feature2<- rnorm(100)
feature3<- rnorm(100)
target1<- rnorm(100)
target2<- rnorm(100)

mydata<- data.frame(feature1, feature2, feature3, target1, target2)
par(mfrow=c(2,3))
features<- c("feature1", "feature2", "feature3")
targets<- c("target1", "target2")
for(i in 1:length(targets)){
  for(j in 1:length(features)){
    plot(mydata[,c(features[j], targets[i])], main = paste0(c(features[j], "vs",targets[i])))
  } }

enter image description here

如果只想针对所有变量绘制所有变量,则可以使用plot(mydata)