Using the inputs shown reproducibly in the Note at the end
as.data.frame(lapply(DF, function(x) c(sum(x %in% products), x)))
## seller_a seller_b seller_c
## 1 6 3 4
## 2 a b d
## 3 d d e
## ...snip...
Numeric vector
however, all elements of a column must be of the same type so the numbers will be coerced to character. You might prefer to just create a separate numeric vector.
sapply(DF, function(x) sum(x %in% products))
## seller_a seller_b seller_c
## 6 3 4
S3
This is probably overdoing it but it would be possible to create a new S3 class that has the product numbers stored as a numeric attribute rather than a row but show it as a row when printed.
as.data.frame1 <- function(x, ...) UseMethod("as.data.frame1")
as.data.frame1.data.frame <- function(x, product, ...) {
out <- structure(x, class = c("data.frame1", class(x)))
attr(out, "product") <- sapply(DF, function(x) sum(x %in% products))
out
}
format.data.frame1 <- function(x, ...) {
format(as.data.frame(rbind(attr(x, "product"), x)))
}
print.data.frame1 <- function(x, ...) {
print(format(x), ...)
}
DF1 <- as.data.frame1(DF, products)
DF1
## seller_a seller_b seller_c
## 1 6 3 4
## 2 a b d
## 3 d d e
## ...snip...
attr(DF1, "product") # numeric vector
## seller_a seller_b seller_c
## 6 3 4
as.data.frame(DF1)
## seller_a seller_b seller_c
## 1 a b d
## 2 d d e
## 3 g g g
## ...snip...
Note
products <- scan(text = "a, b, d, f, g, h, i, j, m, o, t, z",
what = "", sep = ",", strip.white = TRUE)
Lines <- "seller_a seller_b seller_c
a b d
d d e
g g g
h l h
t n t
z y w"
DF <- read.table(text = Lines, header = TRUE)