我有一个名为“ weights”的数据集,我想知道编写以下代码的最有效方法是什么:
public class MainActivity extends AppCompatActivity {
static AudioManager mAudioManager;
static ComponentName mReceiverComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mReceiverComponent = new ComponentName(this, HeadsetBtnReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mReceiverComponent);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onBackPressed() {
Log.e("Udp", "Backpress MainActivity");
finish();
}
@Override
public void onDestroy() {
Log.e("UDP svc", "Destroying MainActivity");
mAudioManager.unregisterMediaButtonEventReceiver(mReceiverComponent);
finish();
super.onDestroy();
}
public static class HeadsetBtnReceiver extends BroadcastReceiver {
// Constructor is mandatory
public HeadsetBtnReceiver()
{
super ();
}
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
Log.e("Udp svc", intentAction.toString() + " happened");
if (!Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
Log.e("Udp svc", "no media button information");
return;
}
KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
Log.e("Udp svc", "no keypress");
return;
}
KeyEvent key = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
Log.e("UDP svc", "KeyEvent : ");
if(key.getAction() == KeyEvent.ACTION_UP) {
int keycode = key.getKeyCode();
if(keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
Log.e("Udp svc", "Next Pressed");
} else if(keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
Log.e("Udp svc", "Previous pressed");
} else if(keycode == KeyEvent.KEYCODE_HEADSETHOOK) {
Log.e("Udp svc", "Head Set Hook pressed");
}
}
}
}
谢谢。我一直在尝试使用带有独特(weights $ Region)的for循环来填充这7个数据帧。
答案 0 :(得分:2)
简而言之,将split
的数据按区域划分为子集,并对每个数据lapply
进行treemap
:
mylist <- split(weights, weights$Region)
result <- lapply(mylist, treemap::treemap, index=c("Level.0","Level.1"), vSize="X2015", type="index")
更新:太好了!这个问题要求“高效”的代码编写方式,而我的带有lapply
的2线式输给了2个for
循环,一个cbind
和一个assign
的答案。好吧,你能做什么...:)
答案 1 :(得分:1)
正如其他人指出的那样,很难弄清,d3treeR
软件包在CRAN上也不可用,因此我不确定这是否可行。使用purrr::map()
library(tidyverse)
library(d3treeR)
myfun <- function(weights, Region, x){
weights %>%
filter(Region %in% x) %>%
treemap(index=c("Level.0","Level.1"), vSize="X2015", type="index")
}
Regions <- c("Canada", "Ontario", "Newfoundland and Labrador", "Prince Edward Island", "Nova Scotia", "New Brunswick", "Quebec")
results <- map(Regions, myfun, weights = weights, Region = Region)
答案 2 :(得分:1)
类似这样的东西:
Bar
如果是这样的话
x <- c("CAN", "ON", "NL", "PE", "NS", "NB", "QC")
weights <- as.data.frame(cbind(weights=rep(c(1,2,3), 7), Region=x))
for(i in x){
y <- weights[weights$Region == i, ]
assign(i, y)
}