1

I want to create a new column in a data frame containing only odd numbers between 1:200. I'm using "cbind" to add the new column, but I'm not sure how to specify that I want only odd numbers. Right now my line of code looks like this

odd <- cbind(rowNA, seq(1:200, by = 2 + 1))

Edit: I'm going to add the rest of Rscript from the assignment I'm working on to see if that helps

# Rassignment 2#

#Q1
#a
nums <- seq(1:100)

#b
tens <- rep(10, times = 100)

#c
ab <- data.frame(nums, tens)

#d
rowNA <- rbind(ab, c(NA))

#e
odd <- cbind(rowNA, seq(1, 200, by = 2))
eak115
  • 13
  • 4

4 Answers4

2

We can use the from, to and by arguments of seq

v1 <- seq(1, 200, by = 2)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you for your reply akrun. I ran that line of code and it worked however when I try to add the line to my cbind command I receive the error "Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 101, 100." – eak115 Nov 23 '20 at 00:56
  • @eak115 It is because you are returing only half the values with `seq` because you used `by = 2`. If you want to create a new column. Use an index i.. `i1 <- c(TRUE, FALSE); rowNA$v1[i1] <- v1` – akrun Nov 23 '20 at 23:27
2

Another option can be using module %% and storing the odd values in a new vector. Then using sample we could make the cbind() with vector having same length:

set.seed(123)
#Data
rowNA <- rep(NA,17)
#Vector
v1 <- 1:200
v2 <- v1[v1%%2==1]
#Assign in function of length of rowNA
v3 <- sample(v2,length(rowNA),replace = T)
#Bind
odd <- cbind(rowNA, v3)

Output:

odd
      rowNA  v3
 [1,]    NA  61
 [2,]    NA 157
 [3,]    NA 101
 [4,]    NA  27
 [5,]    NA 133
 [6,]    NA  83
 [7,]    NA  99
 [8,]    NA  85
 [9,]    NA  27
[10,]    NA  49
[11,]    NA 179
[12,]    NA 181
[13,]    NA 137
[14,]    NA 181
[15,]    NA 113
[16,]    NA 183
[17,]    NA  17

Using a solution like:

#Bind error
odd <- cbind(rowNA, seq(1, 200, by = 2))

Will return next error as elements are from different dimension:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 17, 100
Duck
  • 39,058
  • 13
  • 42
  • 84
1

Using basic mathematics an odd number is 2k+1 if we want to get odd numbers between 1:200 then k = 0:99 implies

2*(0:99) + 1

Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 101, 100

Means that you need to include 201 in the range rewriting the formula to something like 2*(0:100) + 1

Abdessabour Mtk
  • 3,895
  • 2
  • 14
  • 21
0

You can try this approach with seq :

odd <- cbind(rowNA, num = seq(1, by = 2, length.out = nrow(rowNA)))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you for your comment Ronak, I ran this line of code and I received the same "Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 101, 2" as before. – eak115 Nov 23 '20 at 23:12