Working with data frames in R-1

fix: replacement has X row, data has X

x<-data.frame()

x$y<-c(1)

Error in `$<-.data.frame`(`*tmp*`, “y”, value = 1) :
replacement has 1 row, data has 0

Trick here we should consider x as an dimensional matrix, so to work around this error we can use below methods to assign values to a data frame column

> x[1,"y"] <-1
> x[2,"y"] <-1
> x
  y
1 1
2 1

or

x[1:10,“y”] <- 1:10

x
    y
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

class(x)

[1] "data.frame"

or

for(i in 10:20){ x[i,“y”]<- i}

 x
    y
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
20 20

 

 

Advertisement