Codutie
Codutie

Reputation: 1075

How to map array on replicated dataframe

I'm trying to map a vector on my test_replica...

test <- data.frame(a = LETTERS[1:2], b = letters[1:2])
test_replica <- do.call("rbind", replicate(3, test, simplify = F))
vector_to_map <- c("10:10", "10:11", "10:12")

in order to have following result:

  vector_to_map a b
1         10:10 A a
2         10:10 B b
3         10:11 A a
4         10:11 B b
5         10:12 A a
6         10:12 B b

Upvotes: 1

Views: 48

Answers (2)

Mike H.
Mike H.

Reputation: 14360

Following up on my comment you could simply do:

test_replica$vector_to_map <- rep(vector_to_map, each = 2)

#  a b vector_to_map
#1 A a         10:10
#2 B b         10:10
#3 A a         10:11
#4 B b         10:11
#5 A a         10:12
#6 B b         10:12

Or more generally if the length of your vector_to_map is a multiple of the rows in test_replica you could do:

test_replica$vector_to_map <- rep(vector_to_map, each = nrow(test_replica) / length(vector_to_map))

Upvotes: 1

James Thomas Durant
James Thomas Durant

Reputation: 305

I would create a column vector for my "vector to map" and bind it to the data.frame. There are advantages in performance over rbinding it together:

test <- data.frame(a = LETTERS[1:2], b = letters[1:2])
test_replica <- do.call("rbind", replicate(3, test, simplify = F))

x1 <- c(10,10,10)
x2 <- c(10,11,12)

vector_to_map <- paste(rep(x1, each=2), rep(x2, each = 2), sep = ":")

(test_replica <- cbind(vector_to_map, test_replica))

##   vector_to_map a b
## 1         10:10 A a
## 2         10:10 B b
## 3         10:11 A a
## 4         10:11 B b
## 5         10:12 A a
## 6         10:12 B b

Upvotes: 0

Related Questions