DinuJ
DinuJ

Reputation: 81

Issue with getting column names

I have a table like below.(Table1)

Table1:

Type   Fund   Con_counts
5510   COM    1
5520   COM    2
0300   COM    2
5510   COM    1
.

and use the following

Table1 <- Table1[, list(Con_counts = sum(as.double(Con_counts), na.rm = TRUE)), by = list(Type, Fund)] 

How can I get the column names separeted by comma (,) using a code so that I can place within () brackets.

For example, I tried the my code below and does not work.

columns <- colnames(Table2)[!(names(Table2) %in% c("Con_counts"))]

Table1[, list(Con_counts = sum(as.double(Con_counts), na.rm = TRUE)), by = list(columns)]

columns should be Type,Fund

Output: 
    Type   Fund   Con_counts
    5510   COM    2
    5520   COM    2
    0300   COM    2

Upvotes: 1

Views: 163

Answers (2)

Uwe
Uwe

Reputation: 42544

I am sure this answer has been asked before but I have not found a good duplicate.

This is what I would do in data.table syntax using the setdiff() function:

columns <- setdiff(names(Table1), c("Con_counts"))
Table1[, .(Con_counts = sum(as.double(Con_counts), na.rm = TRUE)), by = columns] 
   Type Fund Con_counts
1: 5510  COM          2
2: 5520  COM          2
3:  300  COM          2

Data

library(data.table)
Table1 <- fread(
"  Type   Fund   Con_counts
5510   COM    1
5520   COM    2
0300   COM    2
5510   COM    1")

Upvotes: 1

divibisan
divibisan

Reputation: 12155

Here's a simple solution in dplyr:

library(dplyr)
Table1 <- data.frame(Type = c(5510,5520,0300,5510),
                     Fund = c('COM','COM','COM','COM'),
                     Con_counts = c(1,2,2,1))

Table1 %>%
     group_by(Type,Fund) %>%
     summarise(Con_counts = sum(Con_counts)) %>%

   Type Fund  Con_counts
  <dbl> <fct>      <dbl>
1  300. COM           2.
2 5510. COM           2.
3 5520. COM           2.

If you still want to use data.tables, I can't help you with that, but the answer below can help you get your column names:

To get the column names of Table1, just use colnames(Table1) which returns a character vector.

columns <- colnames(Table1)
columns
[1] 'Type'   'Fund'   'Con_counts'

If you want to remove 'Con_counts from that list, there are several options:

# If you know that 'Con_counts' is the 3rd column,
#   you can call colnames on a sliced version of the data frame
colnames(Table1[,-3])
[1] 'Type'   'Fund'

colnames(Table1[,c(-2,-3)])
[1] 'Type'


# If you want to drop by name
columns <- colnames(Table1)
columns[columns != 'Con_counts']
[1] 'Type'   'Fund'

# If you want to drop by multiple names
columns[!(columns %in% c('Con_counts', 'Type'))]
[1] 'Fund'

You can select those columns by inserting that variable into bracket notation.

Table[1, columns]
# Type   Fund   Con_counts
# 5510   COM    1

Upvotes: 0

Related Questions